I am learning C++ and accidentally wrote
string s = "Some String";;;;
No matter how many semi-colons are there, the compiler won't complain. This works on almost every statement except inside the if block where the compiler says
‘else’ without a previous ‘if’
I am using GCC 4.7
The following is a part of the C++ grammar:
expressionopt;
where the subscript opt indicates that expression is optional.
On the other hand, the grammar for the if statement is:
if(condition)statement
and expressionopt ; is not a valid condition.
The C++ grammar (like C before it) allows null statements. In some cases they're actually even useful. One case is a loop that puts all the actions into the condition, so the body of the loop doesn't need to do anything. A classic example of this is an implementation of the C strcpy function:
while (*d++ = *s++)
;
When you're doing this, you typically do want to put the semicolon on a line by itself like this, not on the end of the same line, like while (*d++ = *s++);. The compiler doesn't care about the difference, but putting it on a separate line helps reassure the reader that loop controlling only a single null statement is intentional. Some people prefer to add a comment as well, like:
while (*d++ = *s++)
/* intentional null statement */ ;
Personally, I think a semicolon on a line by itself is sufficient, but such is life.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With