Is while(1); undefined behavior in C?

后端 未结 4 2015
梦如初夏
梦如初夏 2020-12-01 16:01

In C++11 is it Undefined Behavior, but is it the case in C that while(1); is Undefined Behavior?

4条回答
  •  执笔经年
    2020-12-01 16:32

    The following statement appears in C11 6.8.5 Iteration statements /6:

    An iteration statement whose controlling expression is not a constant expression, that performs no input/output operations, does not access volatile objects, and performs no synchronization or atomic operations in its body, controlling expression, or (in the case of a for statement) its expression-3, may be assumed by the implementation to terminate.

    Since while(1); uses a constant expression, the implementation is not allowed to assume it will terminate.

    A compiler is free to remove such a loop entirely is the expression is non-constant and all other conditions are similarly met, even if it cannot be proven conclusively that the loop would terminate.

提交回复
热议问题