C++核心準(zhǔn)則?NR.1:不要堅(jiān)持所有聲明都應(yīng)該放在函數(shù)頂部

NR.1: Don't insist that all declarations should be at the top of a function
NR.1:不要堅(jiān)持所有聲明都應(yīng)該放在函數(shù)頂部
Reason(原因)
The "all declarations on top" rule is a legacy of old programming languages that didn't allow initialization of variables and constants after a statement. This leads to longer programs and more errors caused by uninitialized and wrongly initialized variables.
“將所有所有聲明放在最上面”規(guī)則是舊編程語(yǔ)言的遺產(chǎn),該編程語(yǔ)言(就是C語(yǔ)言,譯者注)不允許在語(yǔ)句后初始化變量和常量。?這將導(dǎo)致更長(zhǎng)的程序,更多由于變量未初始化或錯(cuò)誤初始化引發(fā)的錯(cuò)誤。
Example, bad(反面示例)
int use(int x)
{
int i;
char c;
double d;
// ... some stuff ...
if (x < i) {
// ...
i = f(x, d);
}
if (i < x) {
// ...
i = g(x, c);
}
return i;
}
The larger the distance between the uninitialized variable and its use, the larger the chance of a bug. Fortunately, compilers catch many "used before set" errors. Unfortunately, compilers cannot catch all such errors and unfortunately, the bugs aren't always as simple to spot as in this small example.
未初始化變量與使用該變量的代碼之間的距離越大,發(fā)生錯(cuò)誤的機(jī)會(huì)越大。幸運(yùn)的是,編譯器可以捕獲許多“設(shè)置前使用”錯(cuò)誤。不幸的是,編譯器無(wú)法捕獲所有此類錯(cuò)誤,這些錯(cuò)誤并不總是像這個(gè)小例子中那樣容易發(fā)現(xiàn)。
Alternative(替代方案)
Always initialize an object
ES.21: Don't introduce a variable (or constant) before you need to use it
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#nr1-dont-insist-that-all-declarations-should-be-at-the-top-of-a-function
新書(shū)介紹
《實(shí)戰(zhàn)Python設(shè)計(jì)模式》是作者最近出版的新書(shū),拜托多多關(guān)注!

本書(shū)利用Python 的標(biāo)準(zhǔn)GUI 工具包tkinter,通過(guò)可執(zhí)行的示例對(duì)23 個(gè)設(shè)計(jì)模式逐個(gè)進(jìn)行說(shuō)明。這樣一方面可以使讀者了解真實(shí)的軟件開(kāi)發(fā)工作中每個(gè)設(shè)計(jì)模式的運(yùn)用場(chǎng)景和想要解決的問(wèn)題;另一方面通過(guò)對(duì)這些問(wèn)題的解決過(guò)程進(jìn)行說(shuō)明,讓讀者明白在編寫(xiě)代碼時(shí)如何判斷使用設(shè)計(jì)模式的利弊,并合理運(yùn)用設(shè)計(jì)模式。
對(duì)設(shè)計(jì)模式感興趣而且希望隨學(xué)隨用的讀者通過(guò)本書(shū)可以快速跨越從理解到運(yùn)用的門(mén)檻;希望學(xué)習(xí)Python GUI 編程的讀者可以將本書(shū)中的示例作為設(shè)計(jì)和開(kāi)發(fā)的參考;使用Python 語(yǔ)言進(jìn)行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書(shū)中的示例為基礎(chǔ),迅速構(gòu)建自己的系統(tǒng)架構(gòu)。
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
