Rectangle 27 1

Is an (empty) infinite loop undefined behavior in C?


@Mehrdad: IMHO it should, but the C++ standard doesn't exclude constant controlling expressions from its version of the rule.

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.

An omitted controlling expression is replaced by a nonzero constant, which is a constant expression.

Just to be sure to capture what all of this means: in C you can write a program where the logic is completely implemented with signal handlers and have the program sit in an infinite loop to wait for an event. This doesn't sound like a very clever implementation of something, but I agree that the language shouldn't prohibit this. In C++ this would be forbidden?

N1570, which is essentially identical to the offical 2011 ISO C standard, says, in section 6.8.5 paragraph 6:

No, the behavior of a for (;;) statement is well defined in C.

The first footnote makes it clear that for (;;) is treated as if it had a constant controlling expression.

The point of the rule is to permit optimizations when the compiler can't prove that the loop terminates. But if the controlling expression is constant, the compiler can trivially prove that the loop does or does not terminate, so the additional permission isn't needed.

This is intended to allow compiler transformations such as removal of empty loops even when termination cannot be proven.

with two footnotes: