这个代码后缀的输出背后的逻辑是什么,并且在一行c ++中的相同变量上有前缀

问题描述 投票:-3回答:1

如何为post increment(a ++)返回5.根据运算符优先级,a ++应该先执行,然后返回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
c++ postfix-mta prefix operator-precedence
1个回答
1
投票

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

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以查看它是否有效以及预期结果是什么。

© www.soinside.com 2019 - 2024. All rights reserved.