Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "true;" (and others) a valid line of code C++?

Adding true; / false; is clearly valid C++ code. It compiles and runs just fine.

Similarly, this is the same for statements like int;, void;, {}(no ()), 1+1;, 1 == 1;, or even just 1; ... why? (I'm using Visual C++)

like image 208
Accumulator Avatar asked Mar 16 '23 06:03

Accumulator


1 Answers

Why not? The language specification clearly states that expression statement in C++ looks as follows

<expression>;

This is exactly what you have in your examples like true; or 1 == 1; or 1;.

The {} is just an empty compound statement.

Meanwhile, int; is ill-formed. If the compiler accepts it quietly, it must be some sort of compiler-specific quirk/bug/extension.

like image 103
AnT Avatar answered Mar 17 '23 18:03

AnT