复合语句一般用来限制变量范围。
例如,
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?