三元运算符和赋值运算符 [英] ternary operator and assignment operator
问题描述
在执行C/C ++三元运算符实际上与赋值运算符具有相同的优先级吗?
卢希恩·格里戈尔(Luchian Grigore)的回答是说
Luchian Grigore's answer says that cases like
a ? b : c = d
将始终被推断为
a ? b : ( c = d )
因为=和?:左右关联,所以
because both = and ?: associate right to left so
在c ++中
k = 21 > 3 ? j = 12 : j = 10;
和
k = 1 > 3 ? j = 12 : j = 10;
都很好.
在C
k = 21 > 3 ? 12 : j = 10
返回错误
invalid lvalue in assignment.
以上不应该推断为(并且不返回错误)
Shouldn't above be inferred as (and return no error)
k= 21 > 3 ? 12 : ( j = 10 )
我认为现在将其分组为
k = ( 21 > 3 ? 12 : j ) = 10
会产生错误,因为在C中(不在C ++中)三元运算符无法返回左值. 在这种情况下,任何人都可以准确地告诉我如何对运算符进行分组.
which gives error since in C(not in C++) ternary operator cannot return lvalue. Can anyone tell me exactly how operators are grouped in this case.
推荐答案
Your linked question's (Does the C/C++ ternary operator actually have the same precedence as assignment operators?) answer by @hvd shows the answer.
?:
的C ++和C语法不同.
The C++ and C grammars for ?:
are different.
在C ++中,最右边的操作数被允许作为赋值表达式(因此,编译器[贪婪地]将=
视为?:
的一部分),而在C语言中,最右边的操作数则是conditional-expression
.因此,在C语言中,只要编译器点击=
,对?:
的分析就完成了,并将其视为k = ( 21 > 3 ? 12 : j ) = 10
.
In C++, the rightmost operand is allowed to be an assignment expression (so the compiler [greedily] treats the =
are part of the ?:
) while in C the rightmost operand is a conditional-expression
instead. Thus in C as soon as the compiler hits the =
the analysis of ?:
is complete and it treats it as k = ( 21 > 3 ? 12 : j ) = 10
.
这篇关于三元运算符和赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!