我可以使用条件运算符来初始化 C 样式字符串文字吗?

Can I use conditional operator to initialize C style string literal?

我正在尝试使用三元运算符 (?:) 将字符数组初始化为一个或另一个字符串

char answ[] = ans > 0 ? "Anton" : "Danik";

其中 ans 只是之前获得的整数,我不断收到错误消息:

initialization with '{...}' expected for aggregate object

难道你根本就不能通过三元运算符来初始化数组吗?


我也试过这个:

char answ[] = { ans>0 ? "Anton" : "Danik" };

错误原因:

value of type "const char *" cannot be used to initialize an entity of type "char"

Is it that you simply can't initialize arrays through a ternary operator?

确实,你不能。

在您的示例中,您不希望只有数组。你想要字符串文字 - 一个特定的数组。不幸的是,编译器不会将 answ 视为一个,因为您尝试使用条件运算符进行初始化。编译器直接将其视为 chars.

的数组

但是声明 C 字符串有不同的方法 - 使用 const 和指针。

const char* answ = ans > 0 ? "Anton" : "Danik";

这种方法的缺点是 const - 您无法修改此字符串。

这就是为什么,如果您使用的是 C++,则应该使用它的字符串 - std::string :

std::string answ = ans > 0 ? "Anton" : "Danik";

在 C 中,您可以这样做:

char answ[6];
ans > 0 ? strcpy(answ, "Anton") : strcpy(answ, "Danik");

但在这一点上,三元运算符只是比正常 if-else 更简洁,所以不要那样做。