Array initialization with a ternary operator?

折月煮酒 提交于 2019-11-29 10:05:20

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};
Grijesh Chauhan

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

Initializer lists are not expressions, so they cannot be used in expressions.

I suggest you leave the array uninitialized and use memcpy.

int why[2];
memcpy( why, 1 == 1 ? (int[2]){1,2} : (int[2]){3,4}, sizeof why );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!