本文介绍了重复使用前缀++运算符时出现未定义的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了有关未定义行为的,其中看到以下语句:

I read this answer about undefined behaviour, where I saw following statement:

++++++i;     // UB, parsed as (++(++(++i)))

我不认为这是不确定的行为。我怀疑,这真的是C ++中的UB吗?如果是,那么如何?

I don't think it is undefined behaviour. I have a doubt, Is it really UB in C++? If yes, then How?

此外,我编写了程序并使用 g ++ prog.cpp -Wall -Wextra -std = gnu ++ 1z进行了编译-pedantic 命令,它工作正常,没有任何警告。

Also, I made program and compiled using g++ prog.cpp -Wall -Wextra -std=gnu++1z -pedantic command, it's working fine without any warning. It's give an expected output.

#include <iostream>
using namespace std;

int main()
{
    int i = 0;
    cout<<++++++i<<endl;
}


推荐答案

在C ++ 03中是未定义的行为。在C ++ 11中不是。各种预增量之间没有序列点。如果 i 是用户定义的类型,则它将是定义良好的行为,因为这样会进行函数调用(一个序列点)。

In C++03 it is undefined behavior. In C++11 it is not. There is no sequence point between the various pre-increments. If i was a user-defined type, it would be well-defined behavior because then there would be a function call (a sequence point).

在C ++ 11中,序列点的概念被之前/之后的序列代替。缺陷637()提供了一个示例,该示例以前未定义的构造变得定义明确( i = ++ i +1 )。

In C++11, the idea of sequence points was replaced with sequenced before/sequenced after. Defect 637 (http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#637) provides an example of a previously undefined construct becoming well-defined (i = ++i + 1).

要了解为什么它不是未定义的行为,让我们看一下需要的部分。 ++ i 等效于 i = i + 1 i 仅被评估一次)。此外,如果我们用 inc 代替 i = i + 1 ,则 ++(i = i + 1)变为 inc = inc + 1

To understand why it's not undefined behavior, let's look at the pieces we need. ++i is equivalent to i = i + 1 (except i is evaluated only once). Further if we substitute i = i + 1 with inc, ++(i = i + 1) becomes inc = inc + 1.

[expr.ass]状态:

[expr.ass] states:

因此, i = i + 1 inc 的值计算之前进行排序;但是,在 inc 的值计算之后,后, inc = inc + 1 中的赋值被排序。因为分配是顺序的,所以没有未定义的行为。

Thus the assignment in i = i + 1 is sequenced before value computation of inc; however, the assignment in inc = inc + 1 is sequenced after value computation of inc. There is no undefined behavior because the assignments are sequenced.

这篇关于重复使用前缀++运算符时出现未定义的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:34