Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 559
Neo Avatar asked Jul 14 '20 07:07

Neo


People also ask

Why do we return 0 in C?

The main function in a C program returns 0 because the main() method is defined and imported first when the code is run in memory. The very first commands within the main() function are implemented. Until all commands of code have been accomplished, the program must be removed from memory.

What is the valid statement in C?

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. 0; is a legal statement.

What does != 0 mean in C?

The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. In fact, !! x is a common idiom for forcing a value to be either 0 or 1 (I personally prefer x != 0 , though).

What does #if 0 mean in C?

>#endif. >What is '0' and how is it 'defined'?! It is the successor to -1, and is defined using the piano axioms. In C, zero is false. Non zero is true.


2 Answers

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

like image 111
Bathsheba Avatar answered Sep 27 '22 03:09

Bathsheba


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.

like image 20
xavc Avatar answered Sep 25 '22 03:09

xavc