[英]does subscript evaluate before the right hand side of assignment operator
I'm trying to do something like我正在尝试做类似的事情
arr[getchar()-'a'] = getchar();
is it guaranteed that the subscript here evaluates before anything else?是否保证这里的下标在其他任何事情之前评估?
Before C++17, no guaranty of order C++17之前,不保证顺序
Since C++17: (from C++'s order of evaluation )从C++17 开始:(来自C++ 的求值顺序)
17) In a subscript expression E1[E2], every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2
17) 在下标表达式 E1[E2] 中,E1 的每个值计算和副作用都排在 E2 的每个值计算和副作用之前
20) In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect of E1
20) 在每个简单赋值表达式 E1=E2 和每个复合赋值表达式 E1@=E2 中,E2 的每个值计算和副作用都在 E1 的每个值计算和副作用之前排序
So in your case:所以在你的情况下:
arr[getchar()-'a'] = getchar();
// (2) (3) (1)
No, it's not guaranteed.不,不能保证。 (at least for pre-C++17 code, as others mentioned ).
(至少对于 C++17 之前的代码,正如其他人提到的那样)。
As by the order of evaluation rules (emphasis mine):按照评估规则的顺序(强调我的):
Order of evaluation of any part of any expression, including order of evaluation of function arguments is unspecified [...].
任何表达式的任何部分的求值顺序,包括函数参数的求值顺序是未指定的 [...]。 The compiler can evaluate operands and other subexpressions in any order, and may choose another order when the same expression is evaluated again.
编译器可以以任何顺序计算操作数和其他子表达式,并且在再次计算相同表达式时可以选择其他顺序。
There is no concept of left-to-right or right-to-left evaluation in C++.
C++ 中没有从左到右或从右到左求值的概念。 This is not to be confused with left-to-right and right-to-left associativity of operators: the expression a() + b() + c() is parsed as (a() + b()) + c() due to left-to-right associativity of operator+, but the function call to c may be evaluated first, last, or between a() or b() at run time
这不要与运算符的从左到右和从右到左结合性混淆:表达式 a() + b() + c() 被解析为 (a() + b()) + c( ) 由于 operator+ 的从左到右结合性,但对 c 的函数调用可能会在运行时首先、最后或在 a() 或 b() 之间进行评估
I'm quoting the C++ reference here, but the same holds for C .我在这里引用了 C++ 参考,但同样适用于 C 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.