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
While I don't know the answer, consistency seems like the best argument. Every statement group in C/C++ is either terminated by
Why create a construct which does neither?
If you take a look at C++ grammar, you'll see that the iteration statements are defined as
Note that only
do-while
statement has an;
at the end. So, the question is why thedo-while
is so different from the rest that it needs that extra;
.Let's take a closer look: both
for
and regularwhile
end with a statement. Butdo-while
ends with a controlling expression enclosed in()
. The presence of that enclosing()
already allows the compiler to unambiguously find the end of the controlling expression: the outer closing)
designates where the expression ends and, therefore, where the entiredo-while
statement ends. In other words, the terminating;
is indeed redundant.However, in practice that would mean that, for example, the following code
while valid from the grammar point of view, would really be parsed as
This is formally sound, but it is not really intuitive. I'd guess that for such reasons it was decided to add a more explicit terminator to the
do-while
statement - a semicolon. Of course, per @Joe White's answer there are also considerations of plain and simple consistency: all ordinary (non-compound) statements in C end with a;
.