Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is some_statement;;;; valid in C++? [duplicate]

Tags:

c++

gcc

c++11

g++

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


2 Answers

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.

like image 113
Escualo Avatar answered Apr 02 '26 14:04

Escualo


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.

like image 29
Jerry Coffin Avatar answered Apr 02 '26 14:04

Jerry Coffin