c++ 中的增量和三元运算符优先级
Increment and ternary operator precedence in c++
我想打印以分号分隔的矢量元素。
下面的代码片段产生了一个奇怪的结果:结果从向量的第二个元素开始。任何人都可以写一个解释吗?在这种情况下,迭代器何时递增?
#include <iostream>
int main() {
vector<int> v(10);
for ( int i = 0; i < 10; ++i ) {
v[i] = i;
}
for ( auto it = v.begin(); it != v.end(); )
std::cout << *it << ( (++it != v.end() ) ? ";" : "" );
}
在C++17之前,*it和++it的携带顺序是未指定的。参见,例如,https://en.cppreference.com/w/cpp/language/eval_order
这可以在一个更简单的示例中看到
#include <iostream>
int main() {
int i = 3;
std::cout << i << ++i;
}
我的编译器(带有 -Wall
选项的 Apple LLVM)报告
warning: unsequenced modification and access to 'i' [-Wunsequenced]
std::cout << i << ++i;
~ ^
Order of evaluation of the operands of almost all C++ operators (including the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression) is unspecified.
自 C++17 起有一个特殊的移位规则:
In a shift operator expression E1<<E2
and E1>>E2
, every value computation and side-effect of E1
is sequenced before every value computation and side effect of E2
.
我想打印以分号分隔的矢量元素。 下面的代码片段产生了一个奇怪的结果:结果从向量的第二个元素开始。任何人都可以写一个解释吗?在这种情况下,迭代器何时递增?
#include <iostream>
int main() {
vector<int> v(10);
for ( int i = 0; i < 10; ++i ) {
v[i] = i;
}
for ( auto it = v.begin(); it != v.end(); )
std::cout << *it << ( (++it != v.end() ) ? ";" : "" );
}
在C++17之前,*it和++it的携带顺序是未指定的。参见,例如,https://en.cppreference.com/w/cpp/language/eval_order
这可以在一个更简单的示例中看到
#include <iostream>
int main() {
int i = 3;
std::cout << i << ++i;
}
我的编译器(带有 -Wall
选项的 Apple LLVM)报告
warning: unsequenced modification and access to 'i' [-Wunsequenced]
std::cout << i << ++i;
~ ^
Order of evaluation of the operands of almost all C++ operators (including the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression) is unspecified.
自 C++17 起有一个特殊的移位规则:
In a shift operator expression
E1<<E2
andE1>>E2
, every value computation and side-effect ofE1
is sequenced before every value computation and side effect ofE2
.