为什么会出现错误“表达式不可接受”?

(a > b) ? c = 10 : (a < b) ? c = 20 : c = 30;

为什么此代码会产生一个错误,称为“表达式不可接受”?

错误消息说“ c = 30”,这部分导致了错误。

评论
dquis
dquis

Because ternary operator ?: has precedence over =, the expression is parsed as:

((a > b) ? c = 10 : (a < b) ? c = 20 : c) = 30;

Because you can't "assign" to (a > b) ? c = 10 : (a < b) ? c = 20 : c, your compiler errors. You want:

(a > b) ? c = 10 : (a < b) ? c = 20 : (c = 30);

但是写起来真的更好:

c = (a > b) ? 10 : (a < b) ? 20 : 30;
点赞
评论