源代碼—>預處理—>編譯—>優化—>彙編—>鏈接—>可執行的文件。
預處理器運算符
C 預處理器提供了下列的運算符來幫助您創建宏:
宏延續運算符(\)
一個宏通常寫在一個單行上。但是如果宏太長,一個單行容納不下,則使用宏延續運算符(\)。例如:
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
字符串常量化運算符(#)
在宏定義中,當需要把一個宏的參數轉換爲字符串常量時,則使用字符串常量化運算符(#)。在宏中使用的該運算符有一個特定的參數或參數列表。例如:
#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
int main(void)
{
message_for(Carole, Debra);
return 0;
}
<stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
int main(void)
{
message_for(Carole, Debra);
return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果:
Carole and Debra: We love you!
and Debra: We love you!
#include <stdio.h>
#define PSQR(x) printf ("The square of " #x" is %d\n", ((x)*(x)))
int main (void)
{
int y = 2;
PSQR (y);
PSQR (2 + 4);
return 0;
}
輸出結果:
The square of y is 4
The square of 2 + 4 is 36
標記粘貼運算符(##)
宏定義內的標記粘貼運算符(##)會合並兩個參數。它允許在宏定義中兩個獨立的標記被合併爲一個標記。例如:
#include <stdio.h>
#define tokenpaster(n) printf ("token" #n " = %d", token##n)
int main(void)
{
int token34 = 40;
tokenpaster(34);
return 0;
}
<stdio.h>
#define tokenpaster(n) printf ("token" #n " = %d", token##n)
int main(void)
{
int token34 = 40;
tokenpaster(34);
return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果:
token34 = 40
= 40
這是怎麼發生的,因爲這個實例會從編譯器產生下列的實際輸出:
printf ("token34 = %d", token34);
("token34 = %d", token34);
這個實例演示了 token##n 會連接到 token34 中,在這裏,我們使用了字符串常量化運算符(#)和標記粘貼運算符(##)。
defined() 運算符
預處理器 defined 運算符是用在常量表達式中的,用來確定一個標識符是否已經使用 #define 定義過。如果指定的標識符已定義,則值爲真(非零)。如果指定的標識符未定義,則值爲假(零)。下面的實例演示了 defined() 運算符的用法:
#include <stdio.h>
#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif
int main(void)
{
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
<stdio.h>
#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif
int main(void)
{
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果:
Here is the message: You wish!
is the message: You wish!
參數化的宏
CPP 一個強大的功能是可以使用參數化的宏來模擬函數。例如,下面的代碼是計算一個數的平方:
int square(int x) {
return x * x;
}
square(int x) {
return x * x;
}
我們可以使用宏重寫上面的代碼,如下:
#define square(x) ((x) * (x))
square(x) ((x) * (x))
在使用帶有參數的宏之前,必須使用 #define 指令定義。參數列表是括在圓括號內,且必須緊跟在宏名稱的後邊。宏名稱和左圓括號之間不允許有空格。例如:
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void)
{
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
<stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void)
{
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
當上面的代碼被編譯和執行時,它會產生下列結果:
Max between 20 and 10 is 20
between 20 and 10 is 20