Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax with missed Expression for basic for-loop

Tags:

java

c

for-loop

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?

like image 643
Walery Strauch Avatar asked Feb 10 '16 17:02

Walery Strauch


1 Answers

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 contained Statement 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 type boolean or Boolean, 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.

enter image description here

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.

like image 113
Makoto Avatar answered Oct 03 '22 02:10

Makoto