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
?
The rationale starts in JLS 14.14.1.1 and continues into 14.14.1.2, emphasis mine.
If the
ForInit
part is not present, no action is taken.If the
Expression
is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the containedStatement
is executed...
The JLS permits the blank ForInit
, Expression
and ForUpdate
statements and has conditions to deal with their absence, so omitting them is acceptable.
It is not permissible to do so with while
loops, per JLS 14.12.
The
Expression
must have typeboolean
orBoolean
, or a compile-time error occurs.
From this, the specification is not permitting a blank expression to be passed through, since that would result in a compile-time error per above.
If you're looking for a slightly more historical reason, the C specification mandates this as well.
Since Java took heavy inspiration from C (and is mostly implemented in it), it makes perfect sense for Java's loops to behave similarly to C's loops, and this is how they behave: expressions are optional in C's for
statement, and mandatory in its while
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With