这有相当多的优势。
First, variables that are defined only when needed are given context by the statements around them. If x were defined at the top of the function, we would have no idea what it was used for until we scanned the function and found where it was used. Defining x amongst a bunch of input/output statements helps make it obvious that this variable is being used for input and/or output.
首先,只有在需要时才定义的变量是在它们的语句中给出的。如果被定义在功能的顶部,我们将不知道它是什么,直到我们扫描的功能,并发现它被使用。定义一堆输入/输出语句之间的定义有助于使其明显的是,这个变量被用于输入和/或输出。
Second, defining a variable only where it is needed tells us that this variable does not affect anything above it, making our program easier to understand and requiring less scrolling.
其次,定义一个变量,只有在它的需要告诉我们,这个变量不影响上面的任何东西,使我们的程序更容易理解,需要较少的滚动。
Finally, it reduces the likelihood of inadvertently leaving a variable uninitialized, because we can define and then immediately initialize it with the value we want it to have.
最后,它减少了无意中留下一个变量未初始化的可能性,因为我们可以定义然后立即初始化它的价值我们要有。
Rule: Define variables as close to their first use as possible.
规则:尽可能靠近他们的第一次使用定义变量。
好吧,如果这是你的代码,欢迎你做任何你喜欢的。:)但一般,宣告你在变量声明顶部的风格被认为是C++不赞成。我的个人经历告诉我,它会导致更严格的阅读/理解代码,甚至当他们评论。
One issue with declare-at-the-top style of declaration is that you often have to scroll up to find out whether a variable is a local variable (declared in the function) or a function parameter. Declare-when-needed often doesn’t suffer from this wasted energy, since the majority of variables in a function will be declared when needed and used immediately thereafter.
在声明的顶部声明的一个问题是,你经常需要滚动来找出一个变量是一个局部变量(在函数中声明)或函数参数。当需要的时候,通常不会遭受这种浪费的能量,因为在一个函数中的大多数变量将被声明为在其后的时候需要和使用。
//pv prefix means it is a parameter value
//lv prefix means it is a local variable
int add(int pvVal1, int pvVal2)
{
int lvResult = pvVal1 + pvVal2;
return lvResult;
}
关于声明变量的问题。
I am a bit old-style programmer and i cant find the arguments for declare variables when used to be so good.
我是一个有点老风格的程序员,我找不到的参数声明变量时,使用是如此好。
Here is my reasoning (proove me wrong, so i can change my style :)
这是我的推理(证明我是错的,所以我可以改变我的风格:)
Lets see if we have 1000 lines of code. We have a function of 300 lines somewere inside (among other functions).
让我们看看是否有1000行代码。我们有一个300线出现在函数(在其他功能)。
If we use function variables more than once inside that function, and they are declared on their first use, isnt it harder, later on, to find out which one is global and which is declared within those 300 lines?
如果我们使用函数变量不止一次在这个函数里面,并且它们被声明在他们的第一次使用,而不是更难,后来,找出哪一个是全局的,哪个是在这300行中声明的?
Or just if we had all function variables just under function name - you can see on first glance which one is there and which one is global?
或者,如果我们有所有的函数变量只是根据功能名称-你可以看到第一眼,其中一个是全球?