使用复合语句(语句块{...})强制变量局部性

复合语句一般用来限制变量范围。
例如,

for (int i = 0; i < 100; ++i) {
    int value = function(i); // 'value'是{...}中的局部变量。
    cout << i << " " << value <<endl;
}

"value"的作用范围被限制,只能在循环中使用。

除此之外,还有一类不太常见的naked compound statement(即不与if,for,while语句连接的复合语句)。

比较如下两种交换变量的方式:

int x = ???
int y = ???

// Swap `x` and `y`
int tmp = x;
x = y;
y = tmp;

能否写成如下形式:

int x = ???
int y = ???

// Swap `x` and `y`
{
    int tmp = x;
    x = y;
    y = tmp;
}

这看起来很丑,但却是能强制执行变量局部性并使代码更安全

例如:

Object function(ParameterType arg) {
    Object obj = new Object(obj);
    File file = File.open("output.txt", "w+");
    file.write(obj.toString());

    // `obj` is used more here but `file` is never used again.
    ...
}

写成如下形式,通过限制局部变量,使代码更安全,是令变量作用域更小的good practice

RET_TYPE function(PARAM_TYPE arg) {
    Object obj = new Object(obj);
    {
       File file = File.open("output.txt", "w+");
       file.write(obj.toString());
    }

    // `obj` is used more here but `file` is never used again.
    ...
}

参考链接:
[1] Using compound statements (“{” … “}” blocks) to enforce variable locality
[2] Is the usage of internal scope blocks within a function bad style?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值