I have a doubt in Left Shift Operator
int i = 1;
i <<= (sizeof (int) *8);
cout << i;
It prints 1.
How and Why it is 1?
As cnicutar said, your example exhibits undefined behaviour. That means that the compiler is free to do whatever the vendor seems fit, including making demons fly out your nose or just doing nothing to the value at hand.
What you can do to convince yourself, that left shifting by the number of bits will produce 0
is this:
int i = 1;
i <<= (sizeof (int) *4);
i <<= (sizeof (int) *4);
cout << i;
Let's say sizeof(int)
is 4 on your platform. Then the expression becomes:
i = i << 32;
The standard says:
6.5.7-3
If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With