定义不同类型的宏函数

2018-01-17  本文已影响0人  xyyquier

宏函数

 

1. ## :C语言中的##是连接符,将宏参数与之前的token(参数/字符串空格等)连接起来。

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;

}

使用 ## 定义了根据传入参数确定类型的函数,当传入int时,我们定义了 int int_max(int, int)函数,传入float时,定义了float float_max(float ,float)函数。

当然,可以直接定义 #define MAX(x,y) ((x) > (y) ? (x):(y)),此宏函数不会对参数做检查。不管传入int还是float都会按照int或者float比较。

上一篇下一篇

猜你喜欢

热点阅读