在初始化使用新声明的变量(INT X = X + 1)? [英] Using newly declared variable in initialization (int x = x+1)?
问题描述
我只是偶然发现了一个行为,让我吃惊:
当写:
INT X = X + 1;
在C / C ++ - 程序(或涉及新创建的变量x更加复杂的前pression)我的gcc / g ++的编译没有错误。在上述情况下,X是1之后。需要注意的是在范围上没有变量x由previous声明。
所以我想知道这是否是正确的行为(甚至可能在某些情况下非常有用),与一般的我的gcc版本或GCC或只是一个解析器特征模拟。
BTW:下不工作:
INT X ++;
随着前pression:
INT X = X + 1;
变量 X
进入在 =
的标志,这就是为什么你可以使用它在正确的存在右手边。通过开始存在,我指的是变量存在,但尚未被初始化器部分被分配一个值。
不过,除非你初始化静态存储持续时间(例如,函数外)一个变量,它是不确定的行为,因为 X
即开始存在有任意值。
C ++ 03有这样一段话:
申报为名称的点是立即其完整的声明符(第8条)后,和它的初始化之前(如果有的话)...
例如:结果
INT X = 12;
结果
{INT X = X; }
结果
在这里,第二个X初始化它自己(不确定)值。
块引用>这是第二个案例有pretty多少你有你的问题。
I just stumbled upon a behavior which surprised me:
When writing:
int x = x+1;
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.
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++;
解决方案With the expression:
int x = x + 1;
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.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 has this to say:
The point of declaration for a name is immediately after its complete declarator (clause 8) and before its initializer (if any) ...
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.
这篇关于在初始化使用新声明的变量(INT X = X + 1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!