Is an (empty) infinite loop undefined behavior in

2019-01-18 06:01发布

问题:

Is an infinite loop like for (;;); undefined behavior in C? (It is for C++, but I don't know about C.)

回答1:

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

N1570, which is essentially identical to the offical 2011 ISO C standard, says, in section 6.8.5 paragraph 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.

with two footnotes:

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

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

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.



回答2:

The rationale for this question with relevance to C++ isn't relevant to C. Section 5.1.2.3p6 states the limits to optimisation, and one of them is:

At program termination, all data written into files shall be identical to the result that execution of the program according to the abstract semantics would have produced.

Now the question becomes "What data would execution according to the abstract semantics have produced?". Assuming a signal interrupts the loop, the program may very well terminate. The abstract semantics would have produced no output prior to that signal being raised, however. If anything, the compiler may optimise the puts("Hello"); away.