NPS*_*NPS 4 c++ variables scope if-statement
Afaik,{ }
代码中的每一对都会创建一个新的范围。即使它只是为了使用而没有任何if
、for
、 function 或其他需要它的语句:
void myFun(void)
{
int a;
{
int local;
}
}
Run Code Online (Sandbox Code Playgroud)
我开始想知道 - 当if
不使用大括号(使用 1 行主体)编写语句时,它是否仍然会创建一个新范围?
voidmyFun(int a)
{
int b;
if (a == 1)
int tmp; // is this one local to if?
else
int tmp2; // or this one?
b = 2; // could I use tmp here?
}
Run Code Online (Sandbox Code Playgroud)
N4140 [stmt.select]/1 读取:
选择语句中的子语句(每个子语句,以语句
else
的形式if
)隐式定义了一个块作用域
所以,代码
if (a == 1)
int tmp; // is this one local to if?
else
int tmp2; // or this one?
Run Code Online (Sandbox Code Playgroud)
相当于
if (a == 1)
{
int tmp; // yes, this one is local to if
}
else
{
int tmp2; // and this one as well
}
Run Code Online (Sandbox Code Playgroud)