请注意,在嵌套块变量可以有名称的变量的内外块。
当这种情况发生时
,
嵌套
变量
“隐藏
”
的外部变量
:
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
|
通过限制变量的范围,你降低程序的复杂性,减少了活性变量数。进一步的,这使得它更容易看到变量的使用。变量声明块内只能在那块(或嵌套的子块)。这可以使程序更容易理解。
摘要
块允许多个语句可用于单个语句通常可以用。
块中声明的变量称为局部变量。这些变量只能在定义它们的块(或在一个嵌套的子块),并尽快结束破坏块。
如果一个变量只在一个块,宣布它在那块。