Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is for(;;); an infinite loop? [duplicate]

Tags:

c++

c

for-loop

I've written infinite loops like this numerous times over the years in both C and C++, but today is the first time I really thought about it -- why is it an infinite loop when the condition clause is empty? One would expect you'd have to write something like for(;true;); to get a valid infinite loop?

while(); doesn't compile nor does while(;);

Anyways, I like the for(;;); syntax and use it often, but is it a special case to treat an empty condition block as true or are there other cases in C or C++ where an empty condition expression is interpreted as true?

like image 679
charunnera Avatar asked Mar 02 '17 03:03

charunnera


1 Answers

The C Standard explicitly describes this behavior of for loops:

C11 Draft Standard §6.8.5.3 2

Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

Similarly, for C++:

C++14 Draft Standard §6.5.3 2

Either or both of the condition and the expression can be omitted. A missing condition makes the implied while clause equivalent to while(true).

like image 162
ad absurdum Avatar answered Sep 28 '22 16:09

ad absurdum