pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

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

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

問題描述

問題 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)!

【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(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)形?)
主站蜘蛛池模板: 游戏版号转让_游戏资质出售_游戏公司转让-【八九买卖网】 | 大连海岛旅游网>>大连旅游,大连海岛游,旅游景点攻略,海岛旅游官网 | 齿轮减速马达一体式_蜗轮蜗杆减速机配电机-德国BOSERL齿轮减速电动机生产厂家 | 蒸汽吸附分析仪-进口水分活度仪|康宝百科| 柔软云母板-硬质-水位计云母片组件-首页-武汉长丰云母绝缘材料有限公司 | 净气型药品柜-试剂柜-无管道净气型通风柜-苏州毕恩思 | 石油/泥浆/不锈钢防腐/砂泵/抽砂泵/砂砾泵/吸砂泵/压滤机泵 - 专业石油环保专用泵厂家 | 耐火砖厂家,异形耐火砖-山东瑞耐耐火材料厂 | 北京三友信电子科技有限公司-ETC高速自动栏杆机|ETC机柜|激光车辆轮廓测量仪|嵌入式车道控制器 | 壹作文_中小学生优秀满分作文大全 | 生态板-实木生态板-生态板厂家-源木原作生态板品牌-深圳市方舟木业有限公司 | 便携式高压氧舱-微压氧舱-核生化洗消系统-公众洗消站-洗消帐篷-北京利盟救援 | 臻知网大型互动问答社区-你的问题将在这里得到解答!-无锡据风网络科技有限公司 | 广州中央空调回收,二手中央空调回收,旧空调回收,制冷设备回收,冷气机组回收公司-广州益夫制冷设备回收公司 | 手持式线材张力计-套帽式风量罩-深圳市欧亚精密仪器有限公司 | 车载加油机品牌_ 柴油加油机厂家 | 谈股票-今日股票行情走势分析-牛股推荐排行榜 | 游泳池设备安装工程_恒温泳池设备_儿童游泳池设备厂家_游泳池水处理设备-东莞市君达泳池设备有限公司 | 重庆轻质隔墙板-重庆安吉升科技有限公司 | 优考试_免费在线考试系统_培训考试系统_题库系统_组卷答题系统_匡优考试 | 七维官网-水性工业漆_轨道交通涂料_钢结构漆 | 济南品牌设计-济南品牌策划-即合品牌策划设计-山东即合官网 | 哈尔滨发电机,黑龙江柴油发电机组-北方星光 | 工业淬火油烟净化器,北京油烟净化器厂家,热处理油烟净化器-北京众鑫百科 | 不锈钢钢格栅板_热浸锌钢格板_镀锌钢格栅板_钢格栅盖板-格美瑞 | 直流电能表-充电桩电能表-导轨式电能表-智能电能表-浙江科为电气有限公司 | 一体化污水处理设备-一体化净水设备-「山东梦之洁水处理」 | 北京浩云律师事务所-企业法律顾问_破产清算等公司法律服务 | 气动隔膜泵-电动隔膜泵-循环热水泵-液下排污/螺杆/管道/化工泵「厂家」浙江绿邦 | 震动筛选机|震动分筛机|筛粉机|振筛机|振荡筛-振动筛分设备专业生产厂家高服机械 | 济南网站建设|济南建网站|济南网站建设公司【济南腾飞网络】【荐】 | 蓝莓施肥机,智能施肥机,自动施肥机,水肥一体化项目,水肥一体机厂家,小型施肥机,圣大节水,滴灌施工方案,山东圣大节水科技有限公司官网17864474793 | 连续密炼机_双转子连续密炼机_连续式密炼机-南京永睿机械制造有限公司 | 哲力实业_专注汽车涂料汽车漆研发生产_汽车漆|修补油漆品牌厂家 长沙一级消防工程公司_智能化弱电_机电安装_亮化工程专业施工承包_湖南公共安全工程有限公司 | 软装设计-提供软装装饰和软装配饰及软装陈设的软装设计公司 | 活性氧化铝|无烟煤滤料|活性氧化铝厂家|锰砂滤料厂家-河南新泰净水材料有限公司 | 氢氧化钙设备_厂家-淄博工贸有限公司| 制冷采购电子商务平台——制冷大市场 | 大行程影像测量仪-探针型影像测量仪-增强型影像测量仪|首丰百科 大通天成企业资质代办_承装修试电力设施许可证_增值电信业务经营许可证_无人机运营合格证_广播电视节目制作许可证 | 哈尔滨京科脑康神经内科医院-哈尔滨治疗头痛医院-哈尔滨治疗癫痫康复医院 | 找培训机构_找学习课程_励普教育 |