通过限制变量的范围

请注意,在嵌套块变量可以有名称的变量的内外块。 当这种情况发生时 嵌套 变量 “隐藏 的外部变量

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

通过限制变量的范围,你降低程序的复杂性,减少了活性变量数。进一步的,这使得它更容易看到变量的使用。变量声明块内只能在那块(或嵌套的子块)。这可以使程序更容易理解。

摘要

块允许多个语句可用于单个语句通常可以用。

块中声明的变量称为局部变量。这些变量只能在定义它们的块(或在一个嵌套的子块),并尽快结束破坏块。

如果一个变量只在一个块,宣布它在那块。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值