C++进阶:swtich语句特殊的作用域
·
我们知道语句块{ } 会被视为单个语句执行。
在if语句中如果程序员没有在 if statement或者else statement 声明块,编译器将隐式声明一个。
if (condition)
true_statement;
else
false_statement;
实际上相当于
if (condition)
{
true_statement;
}
else
{
false_statement;
}
大多数情况下,这没什么问题。然而,新程序员有时会尝试在隐式块中定义变量,如下所示:
#include <iostream>
int main()
{
if (true)
{
int x{ 5 };
} // x destroyed here
else
{
int x{ 6 };
} // x destroyed here
std::cout << x << '\n'; // x isn't in scope here
return 0;
}
在这种情况下,变量x具有块作用域,并在块结束时被销毁,这一点更加清晰。当我们到达该std::cout行时,x它已经不存在了。
当然因为块作用域的缘故,下面代码将无法运行(当然没有人会这么写代码)。
#include <iostream>
int main()
{
bool contrl { false };
if (contrl)
{
int y {};
std::cout << y << '\n';
}
else
{
y = 5;
std::cout << y << '\n'; // error: ‘y’ was not declared in this scope
}
return 0;
}
然而作为同为控制流语句(选择语句)的switch语句并非如此,它确实可以这么做。
#include <iostream>
int main()
{
switch(2)
{
case 1:
int y; // okay but bad practice: definition is allowed within a case
y = 4;
std::cout << y << '\n';
break;
case 2:
y = 5; // okay: y was declared above, so we can use it here too
std::cout << y << '\n';
break;
case 3:
break;
}
return 0;
}

因为switch 中的所有语句都被视为同一作用域的一部分。
如果我们给它加上块会怎么样?----它将会破坏switch这种标签的作用域。
#include <iostream>
int main()
{
switch(2)
{
case 1:
{
int y; // okay but bad practice: definition is allowed within a case
y = 4;
std::cout << y << '\n';
break;
}
case 2:
{
y = 5; // okay: y was declared above, so we can use it here too
std::cout << y << '\n';
break;
}
case 3:
{
break;
}
}
return 0;
}
输出结果如下,加上嵌入块之后,由于case 1,case 2和case 3 之间共有的作用域被分割,而变量y在case 1语句块末尾被销毁后就不能使用,所以当匹配到case 2 中的变量y时,编译器会告诉你y在这个作用域未声明。
更多推荐



所有评论(0)