宏函數(shù)
?
1.?## :C語(yǔ)言中的##是連接符,將宏參數(shù)與之前的token(參數(shù)/字符串空格等)連接起來(lái)。
2.
#include <stdio.h>
#define GEN_MAX(type) \
type type##_max(type x, type y) \
{ \
????????return x > y ? x : y;? ? ? \
}
int main()
{
????????int id1 = 3;
????????int id2 = 4;
????????int id3 = 0;
????????float fd1 = 1.0f;
????????float fd2 = 2.0f;
????????float fd3 = 0.5f;
????????GEN_MAX(int);
????????fprintf(stdout,"max %d and %d? is %d\n", id1, id2, int_max(id1,id2));
????????fprintf(stdout,"max %d and %d? is %d\n", id1, id3, int_max(id1,id3));
????????GEN_MAX(float);
????????fprintf(stdout,"max %f and %f is %f \n", fd1, fd2, float_max(fd1,fd2));
????????fprintf(stdout,"max %f and %f is %f \n", fd1, fd3, float_max(fd1,fd3));
????????return 0;
}
使用 ## 定義了根據(jù)傳入?yún)?shù)確定類型的函數(shù),當(dāng)傳入int時(shí),我們定義了 int int_max(int, int)函數(shù),傳入float時(shí),定義了float float_max(float ,float)函數(shù)。
當(dāng)然,可以直接定義 #define MAX(x,y) ((x) > (y) ? (x):(y)),此宏函數(shù)不會(huì)對(duì)參數(shù)做檢查。不管傳入int還是float都會(huì)按照int或者float比較。