charunnera charunnera -4 years ago 84
C Question

Why is for(;;); an infinite 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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download