gpt4 book ai didi

c++ - 为什么 (c++)*(c++) 在 C++ 中是未定义的行为?

转载 作者:行者123 更新时间:2023-12-02 10:29:35 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why are these constructs using pre and post-increment undefined behavior?

(14 个回答)


6年前关闭。




我对此代码的输出感到困惑:

int c=3;
cout<<(c++)*(c++);

我使用 gcc,输出是 9 ,但是有人说这是未定义的行为,为什么?

最佳答案

问题是“序列点”:

http://en.wikipedia.org/wiki/Sequence_point

A sequence point in imperative programming defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed.

Sequence points also come into play when the same variable is modified more than once within a single expression. An often-cited example is the C expression i=i++, which apparently both assigns i its previous value and increments i. The final value of i is ambiguous, because, depending on the order of expression evaluation, the increment may occur before, after, or interleaved with the assignment. The definition of a particular language might specify one of the possible behaviors or simply say the behavior is undefined. In C and C++, evaluating such an expression yields undefined behavior.[1]



碰巧的是,我在 MSVC(Windows)和 gcc(Linux)上都得到了完全相同的答案——“9”。无论我使用 gcc ("C") 还是 g++ (C++) 编译,我都会收到警告:
$ g++ -o tmp -Wall -pedantic tmp.cpp
tmp.cpp: In function "main(int, char**)":
tmp.cpp:7: warning: operation on "c" may be undefined
$ ./tmp
c=9...

关于c++ - 为什么 (c++)*(c++) 在 C++ 中是未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62859304/

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