c – 反复移动“x << = 1”后,值是否为0?

前端之家收集整理的这篇文章主要介绍了c – 反复移动“x << = 1”后,值是否为0?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道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.

原文链接:https://www.f2er.com/c/114966.html

猜你在找的C&C++相关文章