问题描述
标准中是否有定义从其隐藏的变量中初始化变量的任何内容?
Is there anything in the standard that defines initialing a variable from the variable it shadows?
例如:
int i = 7;
{
int i = i;
}
Visual Studio 2013允许这样做而不会发出警告,并且可以按预期工作.内部的i
变量是7.Clang和GCC但是给我一个警告,关于从其自身进行初始化的初始化变量将不会被初始化.
Visual Studio 2013 allows this without a warning and works as expected. The inner i
variable is 7. Clang and GCC however give me a warning about a initializing variable initializing from itself will be uninitialized.
推荐答案
标准说:
1 名称的声明点紧随其完整的声明符之后 (第8条)及其初始化器(如果有)之前,除非另有说明. [示例:
1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:
int x = 12;
{ int x = x; }
这里第二个x被初始化 具有自己的(不确定的)价值. —完示例]
Here the second x is initialized with its own (indeterminate) value. —end example ]
这正是您的情况.该程序通过访问未初始化的对象表现出未定义的行为.
This is precisely your case. The program exhibits undefined behavior by way of accessing an uninitialized object.
我的VS2013副本为此代码报告了error C4700: uninitialized local variable 'i' used
.不确定为什么您的副本会表现出不同的行为.
My copy of VS2013 reports error C4700: uninitialized local variable 'i' used
for this code. Not sure why your copy behaves differently.
这篇关于初始化阴影变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!