My guess is it just made parsing easier, but I can't see exactly why.
So what does this have ...
do
{
some stuff
}
while(test);
more stuff
that's better than ...
do
{
some stuff
}
while(test)
more stuff
My guess is it just made parsing easier, but I can't see exactly why.
So what does this have ...
do
{
some stuff
}
while(test);
more stuff
that's better than ...
do
{
some stuff
}
while(test)
more stuff
It's because while statements are valid within a do-while loop.
Consider the different behaviors if the semicolon weren't required:
In C/C++ whitespace don't contribute to structure (like e.g. in python). In C/C++ statements must be terminated with a semicolon. This is allowed:
Flow control statement consistency
Considering consistency...
...all these flow-control constructs, end with a semicolon.
But, countering that we can note that of the block-statement forms, only
do while
is semicolon delimited:So, we have ';' or '}', but never a "bare" ')'.
Consistency of statement delimiters
We can at least say that every statement must be delimited by
;
or}
, and visually that helps us distinguish statements.If no semicolon were required, consider:
It's very difficult to visually resolve that to the distinct statements:
By way of contrast, the following is more easily resolved as a
;
immediately after awhile
condition tells you to seek backwards for thedo
, and that the next statement is unconnected to thatwhile
:Does it matter, given people indent their code to make the flow understandable? Yes, because:
Implications to preprocessor use
It's also worth noting the famous preprocessor do-while idiom:
This can be substituted as follows:
...yields...
If the semicolon wasn't part of the
do while
statement, then theif
statement would be interpreted as:...and, because there are two statements after the
if
, it's considered complete, which leaves theelse
statement unmatched.Because you're ending the statement. A statement ends either with a block (delimited by curly braces), or with a semicolon. "do this while this" is a single statement, and can't end with a block (because it ends with the "while"), so it needs a semicolon just like any other statement.
My answer is that, the compiler may get confusion, when we didn't include the semicolon in the termination of
do.....while();
loop. Without this it is not clear about:That's why we include semicolon in the end of
do......while
loop, to indicate the loop is terminating here if the condition is false.C is semicolon-terminated (whereas Pascal is semicolon-separated). It would be inconsistent to drop the semicolon there.
I, frankly, hate the reuse of the while for the do loop. I think repeat-until would have been less confusing. But it is what it is.