5
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; ?

Neo
  • 1,031
  • 2
  • 11
  • 27
  • Does this answer your question? [what's an expression and expression statement in c++?](https://stackoverflow.com/questions/7479946/whats-an-expression-and-expression-statement-in-c) – GSerg Jul 14 '20 at 08:13

2 Answers2

8

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.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    I never knew that `0` was octal literal (not that it matters, `0` is `0` in any base) – Alan Birtles Jul 14 '20 at 08:38
  • 1
    @AlanBirtles: Yes it's a fun fact for the C++ pub quiz section. – Bathsheba Jul 14 '20 at 09:37
  • 1
    Another common use case of a no-op expression is unused parameters. `int func(int x) { (void)x; ... }` is a common way to intentionally and explicitly squelch the unused parameter warning. – Eljay Jul 14 '20 at 11:45
5

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.

xavc
  • 1,245
  • 1
  • 8
  • 14