I am trying to discern the logic behind punctuator usage in C++, particularly the semicolon. This is my progress so far, with some questions:
- A declaration introduces a type, class or object into a scope, e.g.
int i;
- An expression is a sequence of operators and operands, e.g.
a=i+1; i++;
A statement is an expression or a declaration.
()
Parenthesis group parts of an expression and surround tests e.g.if(a==b)
,while(a==b)
,switch(myTestVal)
andfor(int i=0;i<5;i++)
{}
Braces define scope and group statements and initialisation lists for arrays, enums and structs, but why NOT classes! In addition they are required in a switch statement to enclose its body so a break knows where to continue from.,
Commas separate items in a list, e.g. an argument list or array initialisation list.:
Colons are used after labels, such as after the case part of a switch statement and to separate parts of a statement, such as in the tertiary operator '?'.However
;
rather than:
is used to separate the parts of thefor
statement e.g.for(i=0;i<5;i++)
— Why is this?;
Semicolons terminate statements (expressions and declarations) except where they are terminated by)
, or:
e.g. in a test:(a==(c+b*d))
or argument list.
Note that }
does not count as terminating a statement, so after the }
at the end of a function or class declaration a ;
must be used, since the entire declaration is a statement, made up of many other statements.
However, a function or class implementation is not a declaration (since the function or class must already have been declared); therefore it does not count as a statement and so does not have a closing ;
after the closing }
One last oddity: why is a ;
required after a do...while
?