Neo
Neo

Reputation: 1269

why is 0; a valid statement in C++?

int main() {
    int a;
    2;
    4;
    a;
    
    return 0;
}

Why is this piece of code valid (i.e. not raising any compilation error) ? What the computer does when executing 1; or a; ?

Upvotes: 5

Views: 609

Answers (2)

Bathsheba
Bathsheba

Reputation: 234785

Statements like 0;, 4; are no-operations.

Note that the behaviour of your program is undefined since a; is a read of the uninitialised variable a. Oops.

0, for example, is a valid expression (it's an octal literal int type with a value zero).

And a statement can be an expression followed by a semi-colon.

Hence

0;

is a legal statement. It is what it is really. Of course, to change the language now to disallow such things could break existing code. And there probably wasn't much appetite to disallow such things in the formative years of C either. Any reasonable compiler will optimise out such statements.

(One place where you need at least one statement is in a switch block body. ; on its own could issue warnings with some compilers, so 0; could have its uses.)

Upvotes: 8

xavc
xavc

Reputation: 1295

They are expression statements, statements consisting of an expression followed by a semicolon. Many statements (like a = 3;, or printf("Hello, World!");) are also expression statements, and are written because they have useful side effects.

As for what the computer does, we can examine the assembly generated by the compiler, and can see that when the expression has no side effects, the compiler is able to (and does) optimise the statements out.

Upvotes: 5

Related Questions