Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization with a ternary operator?

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 :

like image 204
Rudi Rüssel Avatar asked Apr 08 '13 11:04

Rudi Rüssel


2 Answers

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};
like image 100
ouah Avatar answered Oct 22 '22 21:10

ouah


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
like image 2
Grijesh Chauhan Avatar answered Oct 22 '22 21:10

Grijesh Chauhan