問題描述
問題 1:在循環(huán)中聲明變量是好的做法還是壞的做法?
Question #1: Is declaring a variable inside a loop a good practice or bad practice?
我已經(jīng)閱讀了其他線程關(guān)于是否存在性能問題(大多數(shù)人說沒有),并且您應(yīng)該始終將變量聲明為靠近它們將要使用的位置.我想知道的是這是否應(yīng)該避免,或者它是否真的是首選.
I've read the other threads about whether or not there is a performance issue (most said no), and that you should always declare variables as close to where they are going to be used. What I'm wondering is whether or not this should be avoided or if it's actually preferred.
示例:
for(int counter = 0; counter <= 10; counter++)
{
string someString = "testing";
cout << someString;
}
問題 2:大多數(shù)編譯器是否意識到該變量已經(jīng)被聲明而只是跳過該部分,還是實(shí)際上每次都在內(nèi)存中為其創(chuàng)建一個位置?
Question #2: Do most compilers realize that the variable has already been declared and just skip that portion, or does it actually create a spot for it in memory each time?
推薦答案
這是優(yōu)秀實(shí)踐.
通過在循環(huán)內(nèi)創(chuàng)建變量,您可以確保它們的作用域被限制在循環(huán)內(nèi).它不能在循環(huán)外被引用或調(diào)用.
By creating variables inside loops, you ensure their scope is restricted to inside the loop. It cannot be referenced nor called outside of the loop.
這樣:
如果變量的名稱有點(diǎn)通用"(如i"),則沒有將它與代碼后面某個地方的另一個同名變量混合的風(fēng)險(也可以使用
-Wshadow
GCC 上的警告說明)
If the name of the variable is a bit "generic" (like "i"), there is no risk to mix it with another variable of same name somewhere later in your code (can also be mitigated using the
-Wshadow
warning instruction on GCC)
編譯器知道變量作用域僅限于循環(huán)內(nèi)部,因此如果該變量被錯誤地引用到別處,則會發(fā)出正確的錯誤消息.
The compiler knows that the variable scope is limited to inside the loop, and therefore will issue a proper error message if the variable is by mistake referenced elsewhere.
最后但并非最不重要的一點(diǎn)是,編譯器可以更有效地執(zhí)行一些專用優(yōu)化(最重要的是寄存器分配),因為它知道變量不能在循環(huán)外使用.例如,無需存儲結(jié)果以備后用.
Last but not least, some dedicated optimization can be performed more efficiently by the compiler (most importantly register allocation), since it knows that the variable cannot be used outside of the loop. For example, no need to store the result for later re-use.
簡而言之,你這樣做是對的.
In short, you are right to do it.
但是請注意,變量不應(yīng)該在每個循環(huán)之間保留其值.在這種情況下,您可能需要每次都對其進(jìn)行初始化.您還可以創(chuàng)建一個更大的塊,包含循環(huán),其唯一目的是聲明變量,這些變量必須從一個循環(huán)到另一個循環(huán)保持其值.這通常包括循環(huán)計數(shù)器本身.
Note however that the variable is not supposed to retain its value between each loop. In such case, you may need to initialize it every time. You can also create a larger block, encompassing the loop, whose sole purpose is to declare variables which must retain their value from one loop to another. This typically includes the loop counter itself.
{
int i, retainValue;
for (i=0; i<N; i++)
{
int tmpValue;
/* tmpValue is uninitialized */
/* retainValue still has its previous value from previous loop */
/* Do some stuff here */
}
/* Here, retainValue is still valid; tmpValue no longer */
}
對于問題#2:當(dāng)函數(shù)被調(diào)用時,變量被分配一次.實(shí)際上,從分配的角度來看,它(幾乎)與在函數(shù)開頭聲明變量相同.唯一的區(qū)別是作用域:變量不能在循環(huán)之外使用.甚至可能沒有分配變量,只是重新使用了一些空閑槽(來自其他作用域已結(jié)束的變量).
For question #2: The variable is allocated once, when the function is called. In fact, from an allocation perspective, it is (nearly) the same as declaring the variable at the beginning of the function. The only difference is the scope: the variable cannot be used outside of the loop. It may even be possible that the variable is not allocated, just re-using some free slot (from other variable whose scope has ended).
隨著有限的和更精確的范圍帶來更準(zhǔn)確的優(yōu)化.但更重要的是,它使您的代碼更安全,在閱讀代碼的其他部分時需要擔(dān)心的狀態(tài)(即變量)更少.
With restricted and more precise scope come more accurate optimizations. But more importantly, it makes your code safer, with less states (i.e. variables) to worry about when reading other parts of the code.
即使在 if(){...}
塊之外也是如此.通常,而不是:
This is true even outside of an if(){...}
block. Typically, instead of :
int result;
(...)
result = f1();
if (result) then { (...) }
(...)
result = f2();
if (result) then { (...) }
這樣寫更安全:
(...)
{
int const result = f1();
if (result) then { (...) }
}
(...)
{
int const result = f2();
if (result) then { (...) }
}
差異可能看起來很小,尤其是在這么小的例子上.但是在更大的代碼庫上,它會有所幫助:現(xiàn)在沒有將某些 result
值從 f1()
傳輸?shù)?f2()
的風(fēng)險堵塞.每個result
都嚴(yán)格限制在自己的作用域內(nèi),使其作用更加準(zhǔn)確.從審閱者的角度來看,這要好得多,因為他需要擔(dān)心和跟蹤的遠(yuǎn)程狀態(tài)變量更少.
The difference may seem minor, especially on such a small example.
But on a larger code base, it will help : now there is no risk to transport some result
value from f1()
to f2()
block. Each result
is strictly limited to its own scope, making its role more accurate. From a reviewer perspective, it's much nicer, since he has less long range state variables to worry about and track.
即使是編譯器也會提供更好的幫助:假設(shè)將來在對代碼進(jìn)行一些錯誤更改后,result
未正確使用 f2()
進(jìn)行初始化.第二個版本將簡單地拒絕工作,在編譯時(比運(yùn)行時更好)聲明一條明確的錯誤消息.第一個版本不會發(fā)現(xiàn)任何東西,f1()
的結(jié)果將簡單地進(jìn)行第二次測試,與 f2()
的結(jié)果混淆.
Even the compiler will help better : assuming that, in the future, after some erroneous change of code, result
is not properly initialized with f2()
. The second version will simply refuse to work, stating a clear error message at compile time (way better than run time). The first version will not spot anything, the result of f1()
will simply be tested a second time, being confused for the result of f2()
.
開源工具 CppCheck(C/C++ 代碼的靜態(tài)分析工具)提供了一些極好的提示關(guān)于變量的最佳范圍.
The open-source tool CppCheck (a static analysis tool for C/C++ code) provides some excellent hints regarding optimal scope of variables.
回應(yīng)關(guān)于分配的評論:上述規(guī)則在 C 中適用,但可能不適用于某些 C++ 類.
In response to comment on allocation: The above rule is true in C, but might not be for some C++ classes.
對于標(biāo)準(zhǔn)類型和結(jié)構(gòu),變量的大小在編譯時是已知的.C 中沒有構(gòu)造"這樣的東西,所以當(dāng)函數(shù)被調(diào)用時,變量的空間將被簡單地分配到堆棧中(沒有任何初始化).這就是在循環(huán)內(nèi)聲明變量時成本零"的原因.
For standard types and structures, the size of variable is known at compilation time. There is no such thing as "construction" in C, so the space for the variable will simply be allocated into the stack (without any initialization), when the function is called. That's why there is a "zero" cost when declaring the variable inside a loop.
但是,對于 C++ 類,我對構(gòu)造函數(shù)知之甚少.我想分配可能不會成為問題,因為編譯器應(yīng)該足夠聰明以重用相同的空間,但初始化可能會在每次循環(huán)迭代中進(jìn)行.
However, for C++ classes, there is this constructor thing which I know much less about. I guess allocation is probably not going to be the issue, since the compiler shall be clever enough to reuse the same space, but the initialization is likely to take place at each loop iteration.
這篇關(guān)于在循環(huán)內(nèi)聲明變量,好的做法還是壞的做法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!