Home > Enterprise >  Compound Statement Expression In C
Compound Statement Expression In C

Time:04-14

Below code is not working.

int i = {(void) 999; 100;}; 

Adding parentheses will work. WHY?

int i = ({(void) 999; 100;}); 

There is another way to do this type of assignment:

int i = ((void) 999, 100); 

What make them different?

CodePudding user response:

In this declaration

int i = {(void) 999; 100;}; 

there are used two statements inside the braces

(void) 999; 

and

100;

as initializers.

This is syntactically invalid. To initialize a scalar object using a list enclosed in braces you may use only one assignment expression and neither statements.

This construction

int i = ({(void) 999; 100;});

is also an invalid C construction. However a compound statement enclosed in parentheses may appear as an expression in GNU C. It is its own language extension. The value of the expression is 100. That is the variable i is initialized by the value 100.

This declaration

int i = ((void) 999, 100); 

is the only valid C construction. Within the parentheses there is used the comma operator. The value of the expression is the right most operand of the expression that is 100.

In fact the last declaration is equivalent to

int i = 100;

The compiler should issue a warning that the expression ( void )999 has no effect.

CodePudding user response:

int i = {(void) 999; 100;}; 

(void) means to discard a value. This is not valid in the context of initializers, as an initializer expects a value on the associated structure's slot.

This is valid in the context of a function call, to tell that the returned function's value does not matter and matters only its side effects.

Also, the syntax {(void) 999; 100;} represents either an initializer, or a statement. The contextual position of this code tells it is not a statement, but an initializer. You cannot initialize an integer with a compound initializer like this one. Matter of syntax.

  • Related