问题
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.)
回答1:
The rules haven't changed. It's still technically undefined.
Quoting from the C standard (Section 6.5.7, paragraph 4, of n1548):
The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
It clearly says if E1
is not unsigned or signed with nonnegative value, the behavior is undefined.
回答2:
In the shift operrators >>
or <<
:
operands should be of integral
type or subject to integral 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's implementation defiend
and with <<
undefined behaviour
Quoting from K&R Appendix-A
The shift operators << and >> group left-to-right. For both operators,
each operand must be integral, and is subject to integral the promotions.
The type of the result is that of the promoted left operand.
The result is undefined if the right operand is negative,
or greater than or equal to the number of bits in the left expression's type.
shift-expression:
additive-expression
shift-expression << additive-expression
shift-expression >> additive-expression
The value of E1<<E2 is E1 (interpreted as a bit pattern) left-shifted E2 bits;
in the absence of overflow, this is equivalent to multiplication by 2. The value
of E1>>E2 is E1 right-shifted E2 bit positions. The right shift is equivalent to division
by 2. if E1 is unsigned or it has a non-negative value; otherwise the result is
implementation-defined.
回答3:
Perhaps you were thinking that the right operand is negative?
http://msdn.microsoft.com/en-us/library/336xbhcz(v=vs.80).aspx
来源:https://stackoverflow.com/questions/13411748/undefined-behavior-when-left-operand-is-negative