在 C++ 中最小化变量的范围 [英] Minimalizing variable's scope in C++
问题描述
我现在编程有一段时间了,我已经开始尝试改进我的代码.由于我真的很讨厌创建大量在长函数中只使用一次的变量,因此使用方括号缩短变量范围是一种好习惯吗?IE.而是写作:
I am programming for a while now and I've started trying to improve my code. Since I really hate creating bazillion of variables that are used only once in long function, is it good practice to shorten variable scope by using brackets? i.e. instead writing:
void fcn()
{
int var1;
// some part of fcn
// use of var1;
// rest of fcn
}
写:
void fcn()
{
// some part of fcn
{
int var1;
// use of var100;
}
// rest of fcn
}
推荐答案
是的,尽可能缩小变量范围确实是个好主意.
Yes it is indeed a good idea to keep the scope of variables as tight as possible.
在您的情况下,除非您绝对确定您使用 var1
的代码只会在 fcn
中使用(如果我的经验有任何意义,我往往会误判),您可以将该代码拆分为单独的函数.你的程序会以这种方式更好地扩展,测试也会更简单.否则,像现在一样使用范围块.
In your case, unless you are absolutely certain that your code using var1
will only ever be used in fcn
(and if my experience is anything to go by, I tend to misjudge that), you could split that code out to a separate function. Your program will scale better that way, and testing will also be simpler. Else, use scope blocks as you currently do.
这篇关于在 C++ 中最小化变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!