In C/C++ why does the do while(expression); need a

2020-01-30 07:26发布

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

8条回答
看我几分像从前
2楼-- · 2020-01-30 08:10

While I don't know the answer, consistency seems like the best argument. Every statement group in C/C++ is either terminated by

  1. A semicolon
  2. A brace

Why create a construct which does neither?

查看更多
3楼-- · 2020-01-30 08:14

If you take a look at C++ grammar, you'll see that the iteration statements are defined as

while ( condition ) statement

for ( for-init-statement condition-opt ; expression-opt ) statement

do statement while ( expression ) ;

Note that only do-while statement has an ; at the end. So, the question is why the do-while is so different from the rest that it needs that extra ;.

Let's take a closer look: both for and regular while end with a statement. But do-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 entire do-while statement ends. In other words, the terminating ; is indeed redundant.

However, in practice that would mean that, for example, the following code

do
{
  /* whatever */
} while (i + 2) * j > 0;

while valid from the grammar point of view, would really be parsed as

do
{
  /* whatever */
} while (i + 2)

*j > 0;

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 ;.

查看更多
登录 后发表回答