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

在循環(huán)內(nèi)聲明變量,好的做法還是壞的做法?

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

問(wèn)題描述

問(wèn)題 1:在循環(huán)中聲明變量是好的做法還是壞的做法?

Question #1: Is declaring a variable inside a loop a good practice or bad practice?

我已經(jīng)閱讀了其他線程關(guān)于是否存在性能問(wèn)題(大多數(shù)人說(shuō)沒(méi)有),并且您應(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;
}

問(wèn)題 2:大多數(shù)編譯器是否意識(shí)到該變量已經(jīng)被聲明而只是跳過(guò)該部分,還是實(shí)際上每次都在內(nèi)存中為其創(chuàng)建一個(gè)位置?

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í)踐.

通過(guò)在循環(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"),則沒(méi)有將它與代碼后面某個(gè)地方的另一個(gè)同名變量混合的風(fēng)險(xiǎn)(也可以使用-Wshadow GCC 上的警告說(shuō)明)

  • 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)部,因此如果該變量被錯(cuò)誤地引用到別處,則會(huì)發(fā)出正確的錯(cuò)誤消息.

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)化(最重要的是寄存器分配),因?yàn)樗雷兞坎荒茉谘h(huán)外使用.例如,無(wú)需存儲(chǔ)結(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.

簡(jiǎn)而言之,你這樣做是對(duì)的.

In short, you are right to do it.

但是請(qǐng)注意,變量不應(yīng)該在每個(gè)循環(huán)之間保留其值.在這種情況下,您可能需要每次都對(duì)其進(jìn)行初始化.您還可以創(chuàng)建一個(gè)更大的塊,包含循環(huán),其唯一目的是聲明變量,這些變量必須從一個(gè)循環(huán)到另一個(gè)循環(huán)保持其值.這通常包括循環(huán)計(jì)數(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 */
}

對(duì)于問(wèn)題#2:當(dāng)函數(shù)被調(diào)用時(shí),變量被分配一次.實(shí)際上,從分配的角度來(lái)看,它(幾乎)與在函數(shù)開頭聲明變量相同.唯一的區(qū)別是作用域:變量不能在循環(huán)之外使用.甚至可能沒(méi)有分配變量,只是重新使用了一些空閑槽(來(lái)自其他作用域已結(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).

隨著有限的和更精確的范圍帶來(lái)更準(zhǔn)確的優(yōu)化.但更重要的是,它使您的代碼更安全,在閱讀代碼的其他部分時(shí)需要擔(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 { (...) }
    }

差異可能看起來(lái)很小,尤其是在這么小的例子上.但是在更大的代碼庫(kù)上,它會(huì)有所幫助:現(xiàn)在沒(méi)有將某些 result 值從 f1() 傳輸?shù)?f2() 的風(fēng)險(xiǎn)堵塞.每個(gè)result都嚴(yán)格限制在自己的作用域內(nèi),使其作用更加準(zhǔn)確.從審閱者的角度來(lái)看,這要好得多,因?yà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.

即使是編譯器也會(huì)提供更好的幫助:假設(shè)將來(lái)在對(duì)代碼進(jìn)行一些錯(cuò)誤更改后,result 未正確使用 f2() 進(jìn)行初始化.第二個(gè)版本將簡(jiǎn)單地拒絕工作,在編譯時(shí)(比運(yùn)行時(shí)更好)聲明一條明確的錯(cuò)誤消息.第一個(gè)版本不會(huì)發(fā)現(xiàn)任何東西,f1() 的結(jié)果將簡(jiǎn)單地進(jìn)行第二次測(cè)試,與 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)于分配的評(píng)論:上述規(guī)則在 C 中適用,但可能不適用于某些 C++ 類.

In response to comment on allocation: The above rule is true in C, but might not be for some C++ classes.

對(duì)于標(biāo)準(zhǔn)類型和結(jié)構(gòu),變量的大小在編譯時(shí)是已知的.C 中沒(méi)有構(gòu)造"這樣的東西,所以當(dāng)函數(shù)被調(diào)用時(shí),變量的空間將被簡(jiǎn)單地分配到堆棧中(沒(méi)有任何初始化).這就是在循環(huán)內(nèi)聲明變量時(shí)成本零"的原因.

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.

但是,對(duì)于 C++ 類,我對(duì)構(gòu)造函數(shù)知之甚少.我想分配可能不會(huì)成為問(wèn)題,因?yàn)榫幾g器應(yīng)該足夠聰明以重用相同的空間,但初始化可能會(huì)在每次循環(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)聲明變量,好的做法還是壞的做法?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

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

相關(guān)文檔推薦

How can I read and manipulate CSV file data in C++?(如何在 C++ 中讀取和操作 CSV 文件數(shù)據(jù)?)
In C++ why can#39;t I write a for() loop like this: for( int i = 1, double i2 = 0; (在 C++ 中,為什么我不能像這樣編寫 for() 循環(huán): for( int i = 1, double i2 = 0;)
How does OpenMP handle nested loops?(OpenMP 如何處理嵌套循環(huán)?)
Reusing thread in loop c++(在循環(huán) C++ 中重用線程)
Precise thread sleep needed. Max 1ms error(需要精確的線程睡眠.最大 1ms 誤差)
Is there ever a need for a quot;do {...} while ( )quot; loop?(是否需要“do {...} while ()?環(huán)形?)
主站蜘蛛池模板: 婷婷激情在线 | 国产综合网站 | 久久精品日产第一区二区三区 | 日韩一区二区三区在线看 | 中文字幕人成人 | 精品一二三 | 91麻豆精品国产91久久久久久 | 国产成人精品一区二区三区在线观看 | www.日本三级 | 国产午夜在线观看 | 青青99| 欧美中文字幕一区二区三区亚洲 | 国产成人精品免高潮在线观看 | 亚洲国产精品成人无久久精品 | 在线观看 亚洲 | 中文字幕成人免费视频 | 欧美日韩一卡 | 亚洲欧美日韩成人在线 | 国产精品久久久久久久久免费樱桃 | 国产欧美日韩一区 | 天天影视网天天综合色在线播放 | 午夜精品一区二区三区在线播放 | 99精品在线观看 | 日韩一区二 | 日韩影院在线 | 黄色片大全在线观看 | 国产在线一区二区 | 81精品国产乱码久久久久久 | 在线亚洲欧美 | 国产视频一区二区 | 国产精品日韩在线观看 | 中文字幕啪啪 | 日韩精品在线网站 | 亚洲午夜精品视频 | 久久天天综合 | 青青久久 | 99久久久国产精品 | 亚洲少妇综合网 | 99热热| 日韩国产一区二区三区 | 一区二区三区国产 |