Some days ago I was talking with my colleagues about this code in Java:
for( ; ; ) { }
Nothing special here, just an infinite loop.
But we wonder why this is syntactically correct. If you take a look to JLS §14.14.1 you'll see this:
for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
I understand that ForInit
and ForUpdate
can be omitted. But at least I would expect that Expression
is mandatory, like in while-loop:
while() {} // compile error, Expression is missed
So why can Expression be omitted on a for-loop? And even one think more - why is missed Expression resolved to true
? My expectation would be that empty Expression is resolved to false
.
The same think is valid for other languages (I've try it with C and JavaScript, but I believe every language with for-loops behaves in that way).
Why is an Expression clause not mandatory in for-loop (but in while-loop)? Why does empty Expression resolve to true
and not to false
?