[英]Conditional operator “?:” in C++
Why this statement : 为什么这样说:
int a = 7, b = 8, c = 0;
c = b > a? a > b? a++: b++: a++ ? b++:a--;
cout << c;
is not equal to : 不等于:
int a = 7, b = 8, c = 0;
c = (b > a? (a > b? a++: b++): a++)? b++: a--;
cout << c;
and is equal to : 并且等于:
int a = 7, b = 8, c = 0;
c = b > a? (a > b? a++: b++): (a++? b++: a--);
cout << c;
Please give me some reason. 请给我一些理由。 Why ?
为什么呢
Just put it on multiple lines to see the differences : 只需将其放在多行上以查看差异:
c = b>a // true
? a>b // false
? a++
: b++ // b is incremted = 9; c = 8 (post increment)
: a++
? b++
: a--;
is not equal to : 不等于:
c = ( b>a // true
? ( a>b // false
? a++
: b++ ) // b is incremted = 9
: a++ ) // a = 7 (= 8 after post increment), thus true
? b++ // ... b is incremented = 10, c = 9 (post increment)
: a--;
and is equal to : 并且等于:
c = b>a // true
? ( a>b // false
? a++
: b++ ) // b is incremnted = 9, c = 8 (post increment)
: ( a++
? b++
: a-- );
Also, please note that these (horrible) expressions are deterministic only because the ?: operator is used. 另外,请注意,这些(可怕的)表达式仅是确定性的,因为使用了?:运算符。 This operator is one of the very few operators in the C language where the order of evaluation is actually specified.
该运算符是C语言中为数不多的运算符之一,在运算符中实际上指定了评估顺序 。 Had you written some other abomination like
i++ + ++i;
您是否写过其他一些可憎的内容,例如
i++ + ++i;
then the compiler could have evaluated the left operand or the right operand first, which it picks is not defined in the C language. 那么编译器可能首先评估了左操作数或右操作数,因为它选择的不是C语言定义的。
As a rule of thumb, never use the ++ operator as part of an expression with other operators. 根据经验,切勿将++运算符与其他运算符一起用作表达式的一部分。 Only use it on a line of its own (or as loop iterator).
仅在它自己的一行上使用它(或作为循环迭代器使用)。 Because, against mainstream belief, there is actually never a reason to use it together with other operators.
因为与主流观点相反,实际上从来没有理由将其与其他运营商一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.