iokevins
iokevins

Reputation: 1497

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.

Upvotes: 9

Views: 291

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320641

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".

Upvotes: 5

Michael Burr
Michael Burr

Reputation: 340316

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.

Upvotes: 17

Related Questions