Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does Test Condition of "for(;;)" Succeed?

Insomuch as I understand "for(;;)" has no initial condition, no test condition and no increment condition, and therefore loops forever, I am curious why the test condition succeeds each loop.

Does the empty expression ";" evaluate as true in C? Or is this a special case handled by compilers?

A similar, but unrelated question.

like image 322
iokevins Avatar asked Jan 31 '10 06:01

iokevins


2 Answers

This is by the definition of the for statement in the C language. 6.8.5.3/2 "The for statement":

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

like image 133
Michael Burr Avatar answered Oct 05 '22 11:10

Michael Burr


C language has no such thing as "empty expression". If any expression is missing from the for statement, syntactically it means that the entire expression is omitted, not that it is there, but empty.

A for loop with an omitted second expression loops forever because the specification of for statement says so. I.e. it is a dedicated feature specific to for alone, not something more generic.

Additionaly (a terminological nitpick) only the second expression is really a condition. The first and the third are not really "conditions".

like image 36
AnT Avatar answered Oct 05 '22 10:10

AnT