Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of statements don't require semicolon termination in C++?

Is there a rule regarding which statements don't need to be terminated with a semicolon?

like image 551
unj2 Avatar asked Sep 13 '25 23:09

unj2


1 Answers

Yes, it's covered in section 6, "Statement" of the C++ standard (section 6 of C++03, it may have changed in C++11 but I don't have access to that one at the moment).

There are a large number of statement types and not all of them need to be terminated. For example, the following if is a selection statement:

if (i == 1) {
    doSomething();
}

and there is no requirement to terminate that with a semi-colon.

Of the different statements covered, the requirements are:

Statement type        Termination required?
==============        =====================
labelled statement              N (a)
expression                      Y
compound statements             N (a)
selection statements            N (a)
iteration statements            N (a) (b)
jump statements                 Y
declaration statement           Y

(a) Although it may sometimes appear that these are terminated with a semi-colon, that's not the case. The statement:

if (i == 1) doSomething();

has the semi-colon terminating the inner expression statement, not the compound statement, somthing that should be obvious when you examine the first code segment above that has it inside {} braces.

(b) do requires the semi-colon after the while expression.

like image 144
paxdiablo Avatar answered Sep 15 '25 13:09

paxdiablo