few days back I gave Microsoft GD online exam for internship there. I have always studied that the left shift of negative number is an undefined behavior but that paper had almost 7 questions out of 30 related to shift operators and approx 5 questions were ther which involved shifting negative numbers to left and they had no option saying "undefined behavior". I was shocked to see that . So, my question is that has this C standard changed ? Is this defined now ? sample question :
printf("%d",-1<<10);
I marked its answer as -1024 by the logic 2^10*-1
I even ran this on gcc and it gave me o/p as -1024 nly (when I returned home.)
In the shift operrators
>>
or<<
:operands should be of
integral
type or subject tointegral promotion
.If right operand is negative or greater than the bits in left operand then
Undefined behaviour
if left operand is negative with
>>
then it'simplementation defiend
and with<<
undefined behaviour
Quoting from K&R Appendix-A
The rules haven't changed. It's still technically undefined.
Quoting from the C standard (Section 6.5.7, paragraph 4, of n1548):
It clearly says if
E1
is not unsigned or signed with nonnegative value, the behavior is undefined.Perhaps you were thinking that the right operand is negative?
http://msdn.microsoft.com/en-us/library/336xbhcz(v=vs.80).aspx