c++中的后减量和预减量运算符

  • 本文关键字:运算符 c++ c++ decrement
  • 更新时间 :
  • 英文 :


我有如下两个代码:

#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)

最新更新