Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "()" convert statements into expressions in C++? [duplicate]

Tags:

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?

like image 743
Hind Forsum Avatar asked Sep 13 '18 11:09

Hind Forsum


People also ask

What is difference between expression and statement in C?

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.

What is the difference between a statement and an expression?

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.

What is the difference between an expression and a statement in an imperative programming language?

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.

What is expression and statement in C++?

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.


1 Answers

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.

like image 75
Some programmer dude Avatar answered Oct 19 '22 06:10

Some programmer dude