您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“C++怎么使用符號化常量”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“C++怎么使用符號化常量”吧!
ES.45:避免“魔法常數(shù)”,使用符號化常量
Unnamed constants embedded in expressions are easily overlooked and often hard to understand:
表達式中的無名常量很容易被忽視,通常也難于理解。
Example(示例)
for (int m = 1; m <= 12; ++m) // don't: magic constant 12
cout << month[m] << '\n';
No, we don't all know that there are 12 months, numbered 1..12, in a year. Better:
不是所有人都知道都理解數(shù)字1...12指的是一年中的12個月。好一點的寫法是:
// months are indexed 1..12
constexpr int first_month = 1;
constexpr int last_month = 12;
for (int m = first_month; m <= last_month; ++m) // better
cout << month[m] << '\n';
Better still, don't expose constants
不暴露常量也是比較好的做法:
for (auto m : month)
cout << m << '\n';
Flag literals in code. Give a pass to 0, 1, nullptr, \n, "", and others on a positive list.
標記代碼中的字面量。但是允許0,1,nullptr,\n,“”,還有其他包括在正面清單中的字面量。
到此,相信大家對“C++怎么使用符號化常量”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。