在使用宏定義的時候有一些注意事項
必須注意,要適當?shù)氖褂脠A括號以保證計算次序的正確性。
比如:
# define square(x) x * x
當使用 square(x + 1) 調(diào)用該宏定義的時候會出現(xiàn)什么情況呢?
請見下面例子:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
# define square(x) (x * x)
int main(void)
{
int i = 2;
printf("%d * %d = %d\r\n", i, i, square(i));
printf("%d * %d = %d\r\n", i + 1, i + 1, square(i + 1));
system("pause");
return 0;
}
運行這段函數(shù)得到的輸出為:
2 * 2 = 4
3 * 3 = 5
究其原因,就是在執(zhí)行
printf("%d * %d = %d\r\n", i + 1, i + 1, square(i + 1))
的時候,系統(tǒng)在預編譯之后,把這行代碼替換成了:
printf("%d * %d = %d\r\n", i + 1, i + 1, i + 1 * i + 1)
所以才導致的錯誤。
所以用宏定義時,含參數(shù)時,參數(shù)本身要加(),此外,對參數(shù)的操作整體也要加()。
同時在使用宏的時候,要充分考慮前后的語境,必要的時候親自做一下代換試試,防止出現(xiàn)不必要的錯誤。