【问题标题】:Why does the fist print statement of b in the function print 5 and not 6? [duplicate]为什么函数中b的第一个打印语句打印的是5而不是6? [复制]
【发布时间】:2020-11-18 16:20:31
【问题描述】:

我很困惑。我希望函数中的第一个打印语句会打印 6 而不是 5。因为 a++ + c++ = (1+1) + (3+1) = (2+4 = 6)。

#include <iostream>
#include <string>

int main()
{
    int a = 1;
    int b = 2;
    std::cout << "intitialisation b:"<< b << std::endl;
    int c = 3;
    {
        auto b = ++a + c++;
        std::cout << "increment b in function:" << b << std::endl;
        auto e = b;
        c += ++b;
        std::cout << "increment b in function:" << b << std::endl;
    }
    std::cout << "increment b out function:" << b << std::endl;
    int* p = &a;
    int* q = &b;
    std::cout <<"value pointer:" << *q << std::endl;
    ++(*q);
    std::cout <<"value pointer:" << *q << std::endl;
    *p += a++ + (*p)++;
}
 
intitialisation b:2
increment b in function:5
increment b in function:6
increment b out function:2
value pointer:2
value pointer:3

纳丁

【问题讨论】:

  • ++a 递增后返回值。 c++ 在递增之前返回值。
  • 另外,您的代码和问题文本并不真正匹配。
  • the first print statement first 打印 intitialisation b:2
  • 您之前发布了相同的代码,我们已经知道*p += a++ + (*p)++; 没有好处。如果您的问题只是关于auto b = ++a + c++;,请考虑将您的代码减少到minimal reproducible example。您已经得到一个引用整个代码的答案,但我想如果您更改代码,回答者不会太不高兴

标签: c++


【解决方案1】:

语句的行为

*p += a++ + (*p)++;

未定义。那是因为您在一个未排序的步骤中同时读取和写入 a(有时通过指针)。

这意味着整个程序 是未定义的,这可能有点自相矛盾,包括从概念上讲,在该程序之前已经运行的任何语句。这包括您要询问的具体陈述!

除此之外,++a 的计算结果为 a 的递增值,c++ 的计算结果为 c 的未递增值。因此,如果您的代码中没有未定义的构造,则输出将为 2 + 3,即 5。

【讨论】:

  • 真的是这样吗?我最近看了一个视频,诚然半睡半醒,我的外卖信息是存在可观察行为点,当两个可观察行为点之间存在 UB 时,从那里开始程序就有 UB。你能以某种方式支持它,让它更有说服力吗?有参考吗?
  • 除了最后一句话,你已经写了这个answer,以响应相同的OP,使用相同的代码,就在几个小时前,所以应该很清楚UB部分代码与此问题无关。
  • @cigien 再读一遍。答案说 UB 正在回到过去,这是正确的,我只是不相信它会回到那么远
  • @cigien 我读了我的评论,让我们看看会发生什么
  • @idclev463035818 • 我的一位前同事在Undefined behavior can result in time travel 上写了一篇不错的博文。未定义的行为是噩梦的组成部分。
猜你喜欢
  • 1970-01-01
  • 2018-05-16
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
相关资源
最近更新 更多