一行c ++中同一变量的此代码后缀和前缀输出背后的逻辑是什么

What is logic behind output of this code postfix and prefix on same varible in one line c++

如何 post increment(a++) return 5. 根据运算符优先级 a++ 应该首先执行并且应该 return 4.

#include <iostream>
using namespace std;
int main()
{
    int a=4,b=4;
    cout<<++b<<" "<<b++<<" "<<a++<<" "<<++a<<endl;
    return 0;
}
Output: 6 4 5 6

您应该始终在启用警告的情况下编译您的代码。编译器会告诉你结果可能是未定义的:

prog.cc: In function 'int main()':
prog.cc:6:22: warning: operation on 'b' may be undefined [-Wsequence-point]
     cout<<++b<<" "<<b++<<" "<<a++<<" "<<++a<<endl;
                     ~^~
prog.cc:6:41: warning: operation on 'a' may be undefined [-Wsequence-point]
     cout<<++b<<" "<<b++<<" "<<a++<<" "<<++a<<endl;
                                         ^~~

如果你想在同一个表达式中使用和修改一个变量,你需要检查order of evaluation and sequence rules看它是否有效,以及预期的结果是什么。