問題描述
問題 1:在循環中聲明變量是好的做法還是壞的做法?
Question #1: Is declaring a variable inside a loop a good practice or bad practice?
我已經閱讀了其他線程關于是否存在性能問題(大多數人說沒有),并且您應該始終將變量聲明為靠近它們將要使用的位置.我想知道的是這是否應該避免,或者它是否真的是首選.
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:大多數編譯器是否意識到該變量已經被聲明而只是跳過該部分,還是實際上每次都在內存中為其創建一個位置?
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?
推薦答案
這是優秀實踐.
通過在循環內創建變量,您可以確保它們的作用域被限制在循環內.它不能在循環外被引用或調用.
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.
這樣:
如果變量的名稱有點通用"(如i"),則沒有將它與代碼后面某個地方的另一個同名變量混合的風險(也可以使用
-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)
編譯器知道變量作用域僅限于循環內部,因此如果該變量被錯誤地引用到別處,則會發出正確的錯誤消息.
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.
最后但并非最不重要的一點是,編譯器可以更有效地執行一些專用優化(最重要的是寄存器分配),因為它知道變量不能在循環外使用.例如,無需存儲結果以備后用.
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.
但是請注意,變量不應該在每個循環之間保留其值.在這種情況下,您可能需要每次都對其進行初始化.您還可以創建一個更大的塊,包含循環,其唯一目的是聲明變量,這些變量必須從一個循環到另一個循環保持其值.這通常包括循環計數器本身.
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:當函數被調用時,變量被分配一次.實際上,從分配的角度來看,它(幾乎)與在函數開頭聲明變量相同.唯一的區別是作用域:變量不能在循環之外使用.甚至可能沒有分配變量,只是重新使用了一些空閑槽(來自其他作用域已結束的變量).
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).
隨著有限的和更精確的范圍帶來更準確的優化.但更重要的是,它使您的代碼更安全,在閱讀代碼的其他部分時需要擔心的狀態(即變量)更少.
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 { (...) }
}
差異可能看起來很小,尤其是在這么小的例子上.但是在更大的代碼庫上,它會有所幫助:現在沒有將某些 result
值從 f1()
傳輸到 f2()
的風險堵塞.每個result
都嚴格限制在自己的作用域內,使其作用更加準確.從審閱者的角度來看,這要好得多,因為他需要擔心和跟蹤的遠程狀態變量更少.
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.
即使是編譯器也會提供更好的幫助:假設將來在對代碼進行一些錯誤更改后,result
未正確使用 f2()
進行初始化.第二個版本將簡單地拒絕工作,在編譯時(比運行時更好)聲明一條明確的錯誤消息.第一個版本不會發現任何東西,f1()
的結果將簡單地進行第二次測試,與 f2()
的結果混淆.
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++ 代碼的靜態分析工具)提供了一些極好的提示關于變量的最佳范圍.
The open-source tool CppCheck (a static analysis tool for C/C++ code) provides some excellent hints regarding optimal scope of variables.
回應關于分配的評論:上述規則在 C 中適用,但可能不適用于某些 C++ 類.
In response to comment on allocation: The above rule is true in C, but might not be for some C++ classes.
對于標準類型和結構,變量的大小在編譯時是已知的.C 中沒有構造"這樣的東西,所以當函數被調用時,變量的空間將被簡單地分配到堆棧中(沒有任何初始化).這就是在循環內聲明變量時成本零"的原因.
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++ 類,我對構造函數知之甚少.我想分配可能不會成為問題,因為編譯器應該足夠聰明以重用相同的空間,但初始化可能會在每次循環迭代中進行.
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.
這篇關于在循環內聲明變量,好的做法還是壞的做法?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!