gpt4 book ai didi

c++ - 为什么 i =++i + 2 是未定义的行为?

转载 作者:太空狗 更新时间:2023-10-29 22:55:36 25 4
gpt4 key购买 nike

<分区>

我读过一些关于求值顺序的内容,我理解一些由求值顺序引起的错误。

我的基本规则来自文本和示例:

  • Order of operand evaluation is independent of precedence and associativity.
  • In most cases, the order is largely unspecified.

所以对于这样的表达式:int i = f1() * f2();

f1 and f2 must be called before the multiplication can be done. After all, it is their results that are multiplied. However, we have no way of knowing whether f1 will be called before f2 or vice versa.

未定义的行为示例:

int i = 0;
cout << i << " " << ++i << endl;

我的理解:我将 i++i 视为一个函数。我不知道哪个先求值,所以第一个 i 可能是 01 并且(规则)是有道理的。


while(beg != s.end())
*beg = toupper(*beg++); //Just another example.

我认为理解这一点的关键是将每个操作数视为一个“评估单元”,人们不知道这些单元内的评估顺序,但可以知道每个单元中的顺序。

但是对于 i =++i + 2 reference here ,为什么错了?我无法用我自己的结论来解释。

左边的 i 用作左值不是指针++i只是简单的改写了原来的值,并没有改变存储地址。如果先评估或后评估,可能有什么问题?我的规则在这里失败了。

很长,但请尽量提供足够的背景信息,感谢您的耐心等待。


我不知道答案中经常提到的序列点。所以我想我需要先阅读一些相关内容。顺便说一句,辩论不是很有帮助,因为新手只是想知道为什么它被认为是错误的,就像在 C++11 之前一样?


我找到这个答案 Undefined behavior and sequence points很好地解释为什么 i =++i + 2 在 C++11 之前是未定义的行为

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