Why is a for loop's condition optional, but a while loop's isn't? [duplicate]

  • A+

Why is for(;;) treated as an infinite loop while while() gives an error as it requires an expression? Why don't for loops expect expressions, too?


It just… doesn't.

while could have been made to permit an empty condition (which would presumably be interpreted as true), but then it would be asymmetrical with if for which this would make less sense.

Ultimately, there is no compelling reason to permit an empty condition in while preamble as any code using this would not be self-documenting.

For symmetry with for, you could require for(; true; ) — except now this looks weird because the declaration and update clauses may now be empty whereas the condition can't. Okay, let's make those mandatory too. So, what do we put in those places for no-ops? for (int dummy = 0; true; (void)dummy)? Now it's getting silly.

They're different language features and there's no strong reason to make them work the same way in this regard at the expense of other considerations.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: