3 回答

TA貢獻1824條經(jīng)驗 獲得超8個贊
無法調(diào)試宏。 宏觀擴張會導致奇怪的副作用。 宏沒有“命名空間”,因此如果宏與其他地方使用的名稱沖突,則會得到不需要的宏替換,這通常會導致奇怪的錯誤消息。 宏可能會影響你沒有意識到的事情。
1)宏不能調(diào)試。
更換enum
const T
更換
2)宏觀擴張會產(chǎn)生奇怪的副作用。
#define SQUARE(x) ((x) * (x))
x2 = SQUARE(x++)
x2 = (x++) * (x++);
#define safe_divide(res, x, y) if (y != 0) res = x/y;
if (something) safe_divide(b, a, x);else printf("Something is not set...");
更換
3)宏沒有命名空間。
#define begin() x = 0
std::vector<int> v;... stuff is loaded into v ... for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it) std::cout << ' ' << *it;
更換
4)宏有你沒有意識到的效果
#define begin() x = 0#define end() x = 17... a few thousand lines of stuff here ... void dostuff(){ int x = 7; begin(); ... more code using x ... printf("x=%d\n", x); end();}
更換
#define malloc(x) my_debug_malloc(x, __FILE__, __LINE__)#define free(x) my_debug_free(x, __FILE__, __LINE__)
my_debug_malloc
x++ * x++
x
x

TA貢獻1830條經(jīng)驗 獲得超9個贊
將幻數(shù)定義為宏 使用宏替換表達式
隨著新的C+11有一個真正的選擇,經(jīng)過這么多年?
當為魔術數(shù)字定義宏時,編譯器不保留定義值的類型信息。這可能導致編譯警告(和錯誤),并混淆調(diào)試代碼的人員。 當定義宏而不是函數(shù)時,使用該代碼的程序員期望它們像函數(shù)一樣工作,而它們沒有。
#define max(a, b) ( ((a) > (b)) ? (a) : (b) )int a = 5;int b = 4;int c = max(++a, b);
int c = ( ((++a) ? (b)) ? (++a) : (b) ); // after this, c = a = 7
#include <algorithm>
#ifdef max#undef max#endif#include <algorithm>
如果宏作為常量計算為魔術數(shù)字,則不能按地址傳遞它。 對于宏作為函數(shù),您不能使用它作為謂詞,或接受該函數(shù)的地址或?qū)⑵湟暈楹健?/trans>
#define max
template<typename T>inline T max(const T& a, const T& b){ return a > b ? a : b;}
int a = 0;double b = 1.;max(a, b);
max<int>(a, b)
max<double>(a, b)

TA貢獻1995條經(jīng)驗 獲得超2個贊
#define DIV(a,b) a / b printf("25 / (3+2) = %d", DIV(25,3+2));
printf("25 / (3+2) = %d", 25 / 3 + 2);
#define DIV(a,b) (a) / (b)
- 3 回答
- 0 關注
- 276 瀏覽
添加回答
舉報