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;
?
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.
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.
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).
>#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.
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.)
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.
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