Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 748
justinhj Avatar asked Jun 02 '09 22:06

justinhj


People also ask

Why does C require semicolons?

Semicolons are end statements in C. The Semicolon tells that the current statement has been terminated and other statements following are new statements. Usage of Semicolon in C will remove ambiguity and confusion while looking at the code.

What does the semicolon (;) after a statement do?

A semicolon is most commonly used to link (in a single sentence) two independent clauses that are closely related in thought. When a semicolon is used to join two or more ideas (parts) in a sentence, those ideas are then given equal position or rank.


Video Answer


2 Answers

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.

like image 164
Joe White Avatar answered Sep 28 '22 17:09

Joe White


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

like image 24
AnT Avatar answered Sep 28 '22 16:09

AnT