#define PI 3.14; int main() { double r = 10, s = 0; s = r * r * PI; s = PI * r * r; // s = 3.14; * r * r; printf("%f \n",s); return 0; }
在使用#define時 如 #define PI 3.14 最好不要寫成 #define PI 3.14;
這樣程序在預編譯的時候 進行宏替換 會將PI 直接替換成 3.14;當 s=r*r*PI; 時會替換成 s=r*r*3.14;;程序運行時只是產生了空語句,不進行語法報錯,而 s=PI*r*r; 時 會替換成s=3.14;*r*r; 程序報錯
#define int int* void main()
{ int p; #undef int a; return 0; }
上述代碼 程序從上往下進行,在預編譯時會將int 替換成int * #undef 終止宏的有效替換 所以p是個整型指針 a是個整型變量
#define MAX(x,y) ((x)>(y))?(x):(y) int Max(int a,int b) { return a>b? a:b; } int main() { int a = 10, b = 5; double x=12.23,y = 34.45; double c = Max(x,y); c = MAX(x,y); c = MAX(a,b); printf("%d ",a); return 0; }
程序在預編譯的時候 看到c=MAX(x,y),將替換成 c=((12.23)>(34.45))?(12.23):(34.45); 即c=34.45;
區別於Max(a,b); 是函數調用
#define SUM(x,y) ((x * y)) int main() { int a = 3, b = 4; int c = SUM(a+5,b+6); // int c = (a+5*b+6); printf("%d \n",c); return 0; }
在預編譯的時候替換成
int c = (a+5*b+6); 輸出 29
#define begin { #define end } int main() begin int a = 10; printf("%d ",a); end
通過宏改變了c 語言的語法風格 用begin 於 end 替換了{ }
#include<stdio.h> #define MAX(x,y) ((x)>(y))?x:y int Max(int a,int b) { return a>b?a:b; } int main() { int a = 10, b = 5; //int c= Max(++a,b); // printf("%d\n",c); int x=MAX(++a,b); printf("%d \n",x); return 0; }
宏替換 int x=((++a)>(b))?++a:b: 先對a進行自加 變成11 然后比較 又對a進行自加變成12 賦給 x 所以輸出x為12