久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

在循環內聲明變量,好的做法還是壞的做法?

Declaring variables inside loops, good practice or bad practice?(在循環內聲明變量,好的做法還是壞的做法?)
本文介紹了在循環內聲明變量,好的做法還是壞的做法?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

問題 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模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How can I read and manipulate CSV file data in C++?(如何在 C++ 中讀取和操作 CSV 文件數據?)
In C++ why can#39;t I write a for() loop like this: for( int i = 1, double i2 = 0; (在 C++ 中,為什么我不能像這樣編寫 for() 循環: for( int i = 1, double i2 = 0;)
How does OpenMP handle nested loops?(OpenMP 如何處理嵌套循環?)
Reusing thread in loop c++(在循環 C++ 中重用線程)
Precise thread sleep needed. Max 1ms error(需要精確的線程睡眠.最大 1ms 誤差)
Is there ever a need for a quot;do {...} while ( )quot; loop?(是否需要“do {...} while ()?環形?)
主站蜘蛛池模板: 亚洲综合一区二区三区 | 日韩成人在线免费观看 | 一级做a爰片久久毛片免费看 | 免费黄色a视频 | 国产成人精品一区二区三区四区 | 蜜臀久久99精品久久久久野外 | 日韩美女爱爱 | 99福利网| 国产亚洲精品久久久久久豆腐 | 伊人久久精品一区二区三区 | 欧美日韩在线一区 | 午夜在线免费观看 | 在线观看视频福利 | 精品国产一级片 | 国产成人在线一区二区 | 日韩精品一区二区三区视频播放 | 亚洲在线| 一区二区三区四区在线 | 久久久免费精品 | 中文字幕在线一区二区三区 | 久久日韩精品一区二区三区 | 爱草在线 | 欧美日韩在线一区 | 亚洲欧洲精品在线 | 性色综合 | 欧美福利久久 | 久久中文视频 | 欧美黑人一区 | 国产欧美日韩综合精品一区二区 | 欧美二区在线 | 精品国产一区一区二区三亚瑟 | 成人三级网址 | www.激情.com| www亚洲精品 | 精品成人佐山爱一区二区 | 成人欧美一区二区三区在线播放 | 国产高清视频一区 | 欧美日韩福利视频 | 天天综合干 | 超碰免费观看 | 欧美情趣视频 |