gpt4 book ai didi

C++ "operator+="和 "operator++"优先级问题

转载 作者:行者123 更新时间:2023-12-03 08:04:17 28 4
gpt4 key购买 nike

int a = 1;
a += ++a;
cout << a << endl; // 4
int a = 1;
a += a++;
cout << a << endl; // 3

为什么这两个例子有不同的行为?

最佳答案

Warning: the assignments you are looking at have undefined behaviour. See Why are these constructs using pre and post-increment undefined behavior? Also this answer in the question Undefined behavior and sequence points addresses how C++17 resolves these issues.

您的编译器可能以下列方式处理这些操作,解释不同之处:

预增量操作:以下几行:

a=2;
a+=++a;

也是等价的:

a=2;
tmp=++a;
a+=tmp;

内容如下:

  1. 2赋给变量a
  2. 预递增a (++a) 给a 3 赋值给tmp(使其成为 3)
  3. tmp(当前 3)的值增加 a(当前 3)的值,给出我们 6

后增量操作:以下几行:

a=2;
a+=a++;

也是等价的:

a=2;
tmp=a++;
a+=tmp;

内容如下:

  1. 2赋给变量a
  2. 后自增a(a++)首先返回a的原始值(即2)和将它分配给 tmp(使其成为 2),然后将 a 递增到 3
  3. 的值
  4. tmp(当前 2)的值增加 a(当前 3)的值,给出我们 5

关于C++ "operator+="和 "operator++"优先级问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59437369/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com