Variable 1 = ({statement 1; statement 2;}) build in C

main() { int a=10,b=30,c=0; if( c =({a+b;ba;})) { printf("%d",c); } } 

why is the constructor ({;}) legal in C and why does it return the last value of the operator as a result of the expression (why does it work similarly to the comma operator)?

+6
source share
2 answers

This is not the C99 legal standard, but it is a very useful GCC extension called statement-exprs (a parenthesis in brackets enclosed in some expression).

IIRC, some other compilers support this extension, for example. Clang / LLVM

Expression expressions are much more useful when they contain control flow changes and side effects, for example:

  c = 2*({while (a>0) a--,b--; a+b;}); 

However, in your specific case, you can just use a comma

  if (c=(a+b,ba)) 

Since a+b has no side effect, I think that an optimizing compiler could handle this as

  if (c=ba) 

GCC provides other useful extensions , especially local labels , using __label__ and as values with computed gotos (very useful in stream interpreters ...). I don’t know exactly why they were not standardized. I would like them to do this.

+15
source
 main() { int a=10,b=30,c=0; if( c =({a+b;ba;})) { printf("%d",c); } } 

Here {a+b;ba;} is one area. In this, you wrote 2 statements. It is actually regarded as

  { c=a+b; c=ba; } 

The initial value of c is 40 due to a+b . Again c changes to ba . To prove this, we consider three cases.

(1).

  if(c=({(a=a+b);;})) { printf("%d\n",c); printf("%d\n",a); } 

Here o / p - c = 40 and a = 40; Because at the end of the field (ie) in the last statement there is a fictitious (;). therefore c=a+b is o / p. (2)

  if(c=({(a=a+b);ba;})) { printf("%d\n",c); printf("%d\n",a); } 

Here o / p is c = -10, a = 40. Because the last statement is ba . this value is assigned c. (3) main () {

  int a=10,b=30,c=0; if(c=({(a=a+b);0;})) { printf("%d\n",c); printf("%d\n",a); } printf("%d\n",c); } 

Here o / p is only c = 0. If not, due to the last operator 0;

C follows the procedural orientation. And associativity () remains to the right.

+1
source

Source: https://habr.com/ru/post/974670/


All Articles