I don't have access to the C11 specification, therefore I can't investigate this bug.
The following declaration rises an error during compilation:
int why[2] = 1 == 1 ? {1,2} : {3,4};
The error is: expected expression before { and: expected expression before :
This is not valid C11.
You can only initialize an array with an initializer-list not with an expression.
int why[2] = { ... }; // initializer-list {}
Moreover, 1 == 1 ? {1,2} : {3,4}
is not a valid C expression because {1, 2}
is not a C expression.
Just for information using compound literals you can have something close to what you want using a pointer object:
int *why = (1 == 1) ? (int[2]) {1,2} : (int[2]) {3,4};
from Charles Bailey's answer here: Gramma from conditional-expression
conditional-expression:
logical-OR-expression
logical-OR-expression ? expression : conditional-expression
And
1 == 1 ? {1,2} : {3,4};
^ ^ are not expressions
that is the reason compiler gives error like:
error: expected expression before ‘{’ token // means after ?
error: expected expression before ‘:’ token // before :
Edit as @Rudi Rüssel commented:
following is a valid code in c:
int main(){
{}
;
{1,2;}
}
we use {}
to combine statements ;
in C.
note: if I write {1,2}
then its error (*expected ‘;’ before ‘}’ token*)
, because 1,2
is an expression but not a statement.
For OP: what is The Expression Statement in C and what is Block Statement and Expression Statements
edit2:
Note: How @ouah uses typecase to convert it into expression, yes:
To understand run this code:
int main(){
printf("\n Frist = %d, Second = %d\n",((int[2]){1,2})[0],((int[2]) {1,2})[1]);
}
It works like:
~$ ./a.out
Frist = 1, Second = 2
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