我有如下两个代码:
#include <iostream>
int main() {
int a = 4;
if ( a == a--){
std::cout << a << std::endl;
std::cout << "HELLO"<<std::endl;
}
std::cout << a << std::endl;
return 0;
}
输出为:3
和this:
#include <iostream>
int main() {
int a = 4;
if ( a == --a){
std::cout << a << std::endl;
std::cout << "HELLO"<<std::endl;
}
std::cout << a << std::endl;
return 0;
}
输出为:
3
HELLO
3
根据c++运算符优先级,自增和自减运算符(前缀和后缀)在关系运算符==
之前。那么两者的预期输出应该是相同的(这里期望的是:3
),但实际上不是。
帮忙吗?此外,如果上述条件导致未定义的行为,请解释原因。
运算符优先级告诉如何解析表达式(添加括号),而不是求值顺序。
因此--a == b
被有效地解析为(--a) == b
而不是--(a == b)
。