嵌套块被认为是外部块定义它们的部分。因此,外块中声明的变量可以看见里面的嵌套块:
请注意,在嵌套块变量可以有名称的变量的内外块。当这种情况发生时,嵌套变量“隐藏”的外部变量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main()
{ // start outer block
using namespace std;
int x = 5;
{ // start nested block
int y = 7;
// we can see both x and y from here
cout << x << " + " << y << " = " << x + y;
} // y destroyed here
// y can not be used here because it was already destroyed!
return 0;
} // x is destroyed here
请注意,在嵌套块变量可以有名称的变量的内外块。当这种情况发生时,嵌套变量“隐藏”的外部变量:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
int
main() {
//
outer block int
nValue = 5; if
(nValue >= 5) {
//
nested block int
nValue = 10; //
nValue now refers to the nested block nValue. //
the outer block nValue is hidden }
//
nested nValue destroyed //
nValue now refers to the outer block nValue return
0; }
//
outer nValue destroyed |
这是一般的东西,应该是可以避免的,因为它是非常混乱!
变量应该在最有限的范围在声明它们的使用。例如,如果一个变量在一块嵌套使用,它必须在嵌套块声明:
1
2
3
4
5
6
7
8
9
10
|
int
main() { //
do not declare y here { //
y is only used inside this block, so declare it here int
y = 5; cout
<< y; } //
otherwise y could still be used here |