宏定义define的五种常见用法


一、标识常量(宏)(define)

???注意:宏替换是在预处理阶段进行
???第一种用法:
?????#define? M ?10

?????1、使用M代替10这个数字
?????2、可以让数字具备对应的含义。
?????3、可以让代码中使用此数字的,所有一起改变。
?????4、宏的名字一般写成大写的。(规定)
?????5、宏的最后位置不需要使用 ;
?????6、宏的替换是在预处理阶段完成的。

???第二种用法:

点击查看代码
#define    M    10
#define    N    M+10
x = N + N;
y = N*N;      //M+10*M+10=10+10*10+10=120
printf("x = %d, y = %d\n", x , y);     //结果是:40,120
点击查看代码
#define     ADD(x)    x+x

int    m=1,n=2,k=3;
int    sum;
sum = ADD(m+n)*k;  //m+n+m+n*k = 1+2+1+2*3 = 10    (因为:宏替换是在预处理阶段进行,进行宏替换时程序还没有进行算数运算。)

printf("sum = %d\n",sum);

//宏替换是在预处理阶段进行的,m + n=3在程序执行的时候,才会出现结果。所以先进行了宏替换,再执行了运算。
???第三种用法:
点击查看代码
#define  S(a)   #a

printf("S(10) = %s\n ", s(10) );        //结果是;字符类型的“10”
???这里的一个#代表的是字符串化。

???第四种用法:

点击查看代码
#define  NAME(a,b)  a##b
#define  HW  "helloworld"

int hello  =  1000;
printf("hello = %d\n",NAME(h,ello));
printf("hello = %d\n",NAME(he,llo));

printf("HW = %s\n",NAME(H,W));
//执行结果:
//linux@ubuntu:~$./a.out
//hello = 1000
//hello = 1000
//hello = helloworld

???这里的“##”表示的是字符串拼接。

???h##ello ====> hello

???H##w =====>HW

???第五种用法:

点击查看代码
#include 

#define    err_log(msg)    printf(msg);return -1;

int main()
{
    //open(file)
    //如果在程序执行的时候出现了错误,调用err_log来打印
    //错误的日志
    err_log("open file error!");
    return 0;
}

??也可以这样写:
点击查看代码
#include 

#define err_log(msg)  ({printf(msg);return -1;})

int main(int argc, const char *argv[])
{
    err_log("open file error! \n");
    return 0;
}
//执行结果:
//linux@ubuntu:~$gcc test.c
//linux@ubuntu:~$./a.out
//open file error!
点击查看代码
#define print_err(msg) do{perror(msg);return -1;}while(0)
int main(int argc, const char *argv[])
{
    struct  aa  t = {
        .a = "hahahaha",
        .b = 1012,
        .c = 2012,
    };
    int fd;
    if((fd = open("/dev/myled", O_RDWR)) < 0){
        print_err("open");
    }
}

??在宏中,如果有多句话,需要使用({ })将这些多句话括起来。({})内的最后一句话,就是({})内的语句的最终结果;

点击查看代码
//两个数比较大小
#include 

#define    MAX(a,b)        ({int  max; if(a>b)max=a;else max=b;max;})

int main()
{
    int  result_max;
    result_max = MAX(5,10);
    printf("result_max = %d\n",result_max);
    return 0;
}
点击查看代码
//两个数比较大小
#include 

//#define    MAX(a,b)        ({int  max; if(a>b)max=a;else max=b;max;})
#define  MAX(a,b) do{if(a>b) ret=a;else ret=b;}while(0)

int main()
{
    MAX(100,200);
    printf("max = %d\n",ret);
    return 0;
}