Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 686
user541686 Avatar asked Mar 24 '13 05:03

user541686


People also ask

Are infinite loops undefined behavior?

An infinite loop is well defined behavior. Transferring execution to a function and returning is well defined behavior. The compiler can only determine the behavior of the loop based on the declaration of the function.

What is undefined Behaviour in C?

So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.

What is empty loop in C?

An empty loop is a loop which has an empty body, e.g.

Can you have infinite loops in C language?

while loop represents the infinite condition as we provide the '1' value inside the loop condition. As we already know that non-zero integer represents the true condition, so this loop will run infinite times. We can also use the goto statement to define the infinite loop.


1 Answers

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.

like image 189
Keith Thompson Avatar answered Sep 30 '22 19:09

Keith Thompson