The logic of C++ punctuator usage

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) and for(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 the for 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?

Last edited on
There are probably better explanations that I hope others will contribute, but I hope this is illuminating for you.

Stephen Dolley wrote:
They are not required for other conditional statements.
They are required! I think the only case where you don't have to is when the statement inside the conditional is a single statement.

Stephen Dolley wrote:
However ; rather than : is used to separate the parts of the for statement e.g. for(i=0;i<5;i++) - Why is this?
The reason is because the i=0; i<5; i++; are seperate statements.

Stephen Dolley wrote:
One last oddity: why is a ; required after a do...while?
I think that has something to do with the way a do{}while(...); loop works. It checks the condition after it has executed the code contained inside of the do while loop.
Topic archived. No new replies allowed.