数组初始化用三元运算符? [英] Array initialization with a ternary operator?

查看:295
本文介绍了数组初始化用三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有进入C11的规范,所以我不能调查这个bug。

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

错误是:之前预计前$ P $ {pssion和:之前的预期前pression:

The error is: expected expression before { and: expected expression before :

推荐答案

这是无效的C11。

您只能初始化一个初始化列表的数组不能与前pression。

You can only initialize an array with an initializer-list not with an expression.

int why[2] = { ... };  // initializer-list {}

此外, 1 == 1? {1,2} {3,4} 是不是一个有效的C EX pression因为 {1,2} 不是C防爆Ex pression。

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

这篇关于数组初始化用三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆