宏定義中的“#”與“##”

宏定義在C/C++中使用的非常多,一方面定義一些常量,另一方面定義一些通用函數,但是有些宏定義實現較爲複雜,尤其是很多帶#或##的宏定義,令很多人讀起來很不解,下面就簡單介紹一下宏定義中的#和##。

  1. 宏定義裏面有個##表示把字符串聯在一起。如:
#include <stdio.h>
#define CAT(x,y) x##y
int main()
{
    char helloworld[] = "hi, hello world!";
    printf("%s", CAT(hello, world));
    return 0;
}
  1. 宏定義中的#表示將其變爲字符串。如:
#include <stdio.h>
#include<string.h>
#define STRCPY(a, b) strcpy(a ##_p, #b)
int main()
{
    char arrr_p[]="abcdefg";
    char *bb = "123456";
    STRCPY(arrr, bb);
    printf("%s\n",arrr_p);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章