Reputation: 43
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?
Upvotes: 3
Views: 1522
Reputation: 310980
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.
Upvotes: 4