Search code examples
c#iterationsemantics

Statement-terminator (;) operator after iteration statement: Ends the iteration statement itself, or an invisible empty statement?


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?


Solution

  • 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"