c++中謹慎使用#define宏

=============================================================

標題:c++中謹慎使用#define

備註:測試環境爲VC2005

日期:2011.3.11

姓名:朱銘雷

=============================================================

1 使用括號更穩妥

#include <iostream>

#include <cstdlib>

using namespace std;

#define    DOUBLE(x)    x*2

int main()

{

       cout << DOUBLE(1) << endl;

       int i = 1;

       cout << DOUBLE(i+1) << endl;

       system("PAUSE");

}

期望的輸出結果是:

2

4

但實際的輸出結果是:

2

3

原因很簡單,DOUBLE(i+1)展開後1+1*2=3,這違背了DOUBLE宏的初衷。

可修改爲:

#define    DOUBLE(x)    ((x)*2 )

2 必要的時候,用函數代替宏,雖然可能會犧牲點效率

#include <iostream>

#include <cstdlib>

using namespace std;

#define    POWER(x)     ((x)*(x))

int main()

{

       int i = 2;

       cout << POWER(i) << endl;

       cout << POWER(++i) << endl;

       system("PAUSE");

}

期望的輸出結果是:

4

9

但實際的輸出結果是:

4

16

POWER(++i)爲什麼輸出16,可以反彙編看下:

這時候用函數來實現,比用#define宏更穩妥吧,雖然可能效率下降點(多了參數壓棧,CALLRETURN等開銷)。

#include <iostream>

#include <cstdlib>

using namespace std;

int power(int x)

{

       return x*x;

}

int main()

{

       int i = 2;

       cout << power(i) << endl;

       cout << power(++i) << endl;

       system("PAUSE");

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章