溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C++中避免使用宏定義常量或函數(shù)?的原因是什么

發(fā)布時(shí)間:2021-07-28 11:34:42 來源:億速云 閱讀:226 作者:Leah 欄目:大數(shù)據(jù)

C++中避免使用宏定義常量或函數(shù)的原因是什么,針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。

ES.31:不要用宏定義常量或函數(shù)

Reason(原因)

Macros are a major source of bugs. Macros don't obey the usual scope and type rules. Macros don't obey the usual rules for argument passing. Macros ensure that the human reader sees something different from what the compiler sees. Macros complicate tool building.

宏是錯(cuò)誤的主要來源之一。宏不會(huì)遵守通常的范圍和類型準(zhǔn)則。宏也不會(huì)遵守參數(shù)傳遞準(zhǔn)則。宏為人提供一個(gè)和編譯器視角有些不同的視角。宏讓工具構(gòu)建變得更復(fù)雜。

Example, bad(反面示例)

#define PI 3.14#define SQUARE(a, b) (a * b)

Even if we hadn't left a well-known bug in SQUARE there are much better behaved alternatives; for example:

雖然SQUARE定義中不存在已知的錯(cuò)誤,但確實(shí)存在可以動(dòng)作更好的其他選項(xiàng)。

constexpr double pi = 3.14;
template<typename T> T square(T a, T b) { return a * b; }

關(guān)于C++中避免使用宏定義常量或函數(shù)的原因是什么問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI