I have the following code:
int main() { int i=0; int j=({int k=3;++i;})+1; // this line return 0; }
It compiles and runs. If I remove the ()
from "this line", then it doesn't compile.
I'm just curious what syntax rule is being applied here.
The {}
contains 2 statements, and the last statement indicates the "return" value of this code block. Then why does it need an extra ()
pair to make this return value usable?
An expression is something that returns a value, whereas a statement does not. The Big Deal between the two is that you can chain expressions together, whereas statements cannot be chained. Sure statements can be chained.
Statements represent an action or command e.g print statements, assignment statements. Expression is a combination of variables, operations and values that yields a result value.
In programming language terminology, an “expression” is a combination of values and functions that are combined and interpreted by the compiler to create a new value, as opposed to a “statement” which is just a standalone unit of execution and doesn't return anything.
Any variable name (x, y, z, . . . ), constant, or literal is an expression. One or more expressions combined by an operator constitute an expression, e.g., x + y or x * y + z. In several languages, such as Pascal, the assignment is a statement. In C++, it is an expression, e.g., x= y + z.
That's a statement expression, and it's a GCC-specific extension.
From the linked reference:
A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression.
A compound statement is a curly-brace enclosed block of statements.
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