Could any one please help me in understanding the following behaviour.
1 #include <iostream>
2
3 using namespace std;
4
5 main()
6 {
7 uint32_t i = 32;
8
9 // cout << "(1<<32): " << (1<<32) << endl; // - This leads to a compilation error.
10 cout << "(1<<32): " << (1<<i) << endl; // - This compiles and prints 1 - Why?
11
12 return 0;
13 }
If I un-comment the line number 9 above – I see the following compilation error (which makes sense to me)
BitWiseLeftShift.c++: In function 'int main()':
BitWiseLeftShift.c++:9: warning: left shift count >= width of type
But the line number 10 is where my question is. It compiles successfully and prints
(1<<32): 1
something like a circular bit shift. Why would it print 1?
And I have seen that for i == 33, (1<<i) prints 2.
I did search the forum and could not find a relevant question. If this is a duplicate question – please help me with a link.
As pointed out in other answers, if the shift amount is larger or equal to the size of the shifted data in bits (or is negative), the result is undefined.
However, to explain the behavior you are seeing –
Some computer architectures (including x86) treat the shift amount as modulo the size of the data being shifted, so shifting by 32 is equivalent to not shifting at all. To put it another way, they simply mask out the higher bits and use the lower bits.