在初始化中使用新声明的变量(int x = x+1)?

2022-01-18 00:00:00 initialization c c++ undefined-behavior

我偶然发现了一个令我惊讶的行为:

I just stumbled upon a behavior which surprised me:

写作时:

int x = x+1;

在 C/C++ 程序(或涉及新创建的变量 x 的更复杂的表达式)中,我的 gcc/g++ 编译没有错误.在上述情况下,X 之后为 1.请注意,先前声明的范围内没有变量 x.

in a C/C++-program (or even more complex expression involving the newly created variable x) my gcc/g++ compiles without errors. In the above case X is 1 afterwards. Note that there is no variable x in scope by a previous declaration.

所以我想知道这是正确的行为(甚至在某些情况下可能有用)还是只是我的 gcc 版本或一般 gcc 的解析器特性.

So I'd like to know whether this is correct behaviour (and even might be useful in some situation) or just a parser pecularity with my gcc version or gcc in general.

顺便说一句:以下不起作用:

BTW: The following does not work:

int x++;

推荐答案

用表达式:

int x = x + 1;

变量 x 出现在 = 符号处,这就是您可以在右侧使用它的原因.开始存在"是指变量存在,但尚未被初始化部分赋值.

the variable x comes into existence at the = sign, which is why you can use it on the right hand side. By "comes into existence", I mean the variable exists but has yet to be assigned a value by the initialiser part.

但是,除非您正在初始化具有静态存储持续时间的变量(例如,在函数外部),否则这是未定义的行为,因为存在的 x 具有任意值.

However, unless you're initialising a variable with static storage duration (e.g., outside of a function), it's undefined behaviour since the x that comes into existence has an arbitrary value.

C++03 有这样的说法:

C++03 has this to say:

名称的声明点紧接在其完整声明符之后(第 8 条)和初始化器之前(如果有的话)...

The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any) ...

示例:
int x = 12;
<代码>{ int x = x;}
这里第二个 x 用它自己的(不确定的)值初始化.

Example:
int x = 12;
{ int x = x; }
Here the second x is initialized with its own (indeterminate) value.

第二种情况几乎就是您的问题.

That second case there is pretty much what you have in your question.

相关文章