Using newly declared variable in initialization (int x = x+1)?(在初始化中使用新声明的变量(int x = x+1)?)
问题描述
我偶然发现了一个令我惊讶的行为:
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.
这篇关于在初始化中使用新声明的变量(int x = x+1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在初始化中使用新声明的变量(int x = x+1)?
基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01