c++ - 这个后增量语句会导致未定义的行为吗?

标签 c++ undefined-behavior side-effects

<分区>

在使用较新版本的 GCC 构建程序时,我发现代码中存在问题。

count[i] = count[i]++;

此代码适用于较旧版本的 GCC (2.95),但不适用于较新版本 (4.8)。

所以我怀疑此声明会导致未定义的行为,对吗?或者有更好的术语来描述这个问题吗?

最佳答案

这实际上被指定为未定义的行为,因为每个编译器都定义了自己的操作顺序,如以下所述:https://en.cppreference.com/w/cpp/language/eval_order

Order of evaluation of the operands of almost all C++ operators (including the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression) is unspecified. The compiler can evaluate operands in any order, and may choose another order when the same expression is evaluated again.

在cppreference中的自增自减页面其实有警告:https://en.cppreference.com/w/cpp/language/operator_incdec

Because of the side-effects involved, built-in increment and decrement operators must be used with care to avoid undefined behavior due to violations of sequencing rules.

关于c++ - 这个后增量语句会导致未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53000823/

相关文章:

c# - 方法调用中的分配不好的做法?

c++ - 是否有必要为 char 数组调用 delete[] 与 delete?

我可以像这样进行指针运算以避免让指针离开数组边界吗?

c - C 中变量的垃圾值是如何生成的?

python - 为什么全局变量是邪恶的?

c++ - if 语句 - 短路评估与可读性

c++ - 无法为指向类的指针数组创建访问方法

C++:ptr_multimap::insert 的问题

c++ - 为什么 boost::program_options 接受切词?

c++ - 使用复制构造函数创建对象(三类简单规则)会产生运行时错误