我想知道x在以下程序中是否达到零.
请考虑:
int main () { int x = 1; while (x) { x <<= 1; } return 0; }
该程序的预期行为是否正常退出或永久循环?
解决方法
既不是(或两者),当x溢出时,它以未定义的行为运行.
C99规格6.5.7节说:
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 × 2E2,reduced modulo one more than the maximum value representable in the result type. If E1 has a signed
type and nonnegative value,and E1 × 2E2 is representable in the result type,then that is the resulting value; otherwise,the behavior is undefined.