3

During this answer, our beloved Jon Skeet considers the case that do {} while () requires a statement-terminator because while() requires a statement-body, and proceeds to exemplify that:

while (true); (empty statement) or while (true) {} (block statement)

...would be valid.


Things are quite straightforward with the second example; the while-loop executing the compound (block) statement ({}), which is empty.

The first example however, together with Skeet's description, sparked an interesting question to me:

Does the ; in while(true); (or any other iteration statement) terminate the while (/statement) itself (in some sense), or does it terminate an actual invisible empty statement between ) and the terminator?

CosmicGiant
  • 6,275
  • 5
  • 43
  • 58

3 Answers3

3

From a grammar standpoint, it terminates the statement. That's a pretty odd way to think about it though. while loops must have a body, so if you just write

while(true)

The parser doesn't know where the "statement" ends as its missing a token. You could similarly "terminate" the statement with another statement.

while (true) i++;

Is just as valid as just the ;. The way you really should think about it is that writing

while (true) ;

Is really a while loop with an empty statement as its body, not trying to think of what "terminates the statement"

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • 2
    Grammar? According to the spec, a while statement consists of the token `while`, a `(`, a `boolean_expression`, a `)`, and an `embedded_statement`. Then the definition of `embedded_statement` includes a lot of different things, including `block` and `empty_statement`. In fact `embedded_statement` can be all kinds of statements except `labeled_statement` and `declaration_statement`, so these are the only "statements" you cannot use there. For example `while (true) var i = 42;` should be illegal (you can use a block, however). In the example `while (true) ;` there is an `empty_statement`. – Jeppe Stig Nielsen Oct 18 '17 at 22:53
0

A use case for this would be if you had while(something()); it would execute something() till it returns false. So you don't necessarily need a body.

This would be equivalent to something like

while(true){
    if (something()) break;
}

You could use this like an await operator waiting for an action.

NattyMan0007
  • 103
  • 13
0

According to the answer you linked to it's definitely of an empty statement.

From that answer:

There's a semi-colon at the end of every expression statement and declaration statement.

(if, for etc statements aren't expression or declaration statements.)

and while seems to be the same (except that do...while is an exception as mentioned there).

Community
  • 1
  • 1
ispiro
  • 26,556
  • 38
  • 136
  • 291