#和##运算符使用解析

1. #运算符

(1)#运算符用于在预编译期将宏参数转换为字符串

#include <stdio.h>
 
#define CONVERS(x) #x
 
int main()
{
     
    printf("%s\n", CONVERS(Hello world!));
    printf("%s\n", CONVERS(100));
    printf("%s\n", CONVERS(while));
    printf("%s\n", CONVERS(return));
 
    return 0;
}

 

2. #运算符在宏中的妙用

#include <stdio.h>
 
#define CALL(f, p) (printf("Call function %s\n", #f), f(p))
    
int square(int n)
{
    return n * n;
}
 
int f(int x)
{
    return x;
}
 
int main()
{
     
    printf("1. %d\n", CALL(square, 4));
    printf("2. %d\n", CALL(f, 10));
 
    return 0;
}

  结果是: 

Call function square
1. 16
Call function f
2. 10

 

3. ## 运算符

(1)## 运算符用于在预编译期粘连两个符号

#include <stdio.h>
 
#define NAME(n) name##n
 
int main()
{
     
    int NAME(1);
    int NAME(2);
     
    NAME(1) = 1;
    NAME(2) = 2;
     
    printf("%d\n", NAME(1));
    printf("%d\n", NAME(2));
 
    return 0;
}

【利用##定义结构类型】

一般的定义结构体

#include <stdio.h>

struct Test
{
    int i;
    int j; 
};

int main()
{
    struct Test t;  //这样定义每次都要附带上struct
    struct Test tt;
  
}

可能你会想到另一种方式

#include <stdio.h>

typedef struct _tag_Test
{
    int i;
    int j; 
}Test;

int main()
{
    Test t;  //这样就不需要附带struct,但是晦涩
    Test tt;
  
}

最优方式,利用宏来扩展【高效整洁】

#include <stdio.h>
 
#define STRUCT(type) typedef struct _tag_##type type;\
struct _tag_##type
 
STRUCT(Student)
{
    char* name;
    int id;
};
 
int main()
{
     
    Student s1;
    Student s2;
     
    s1.name = "s1";
    s1.id = 0;
     
    s2.name = "s2";
    s2.id = 1;
     
    printf("%s\n", s1.name);
    printf("%d\n", s1.id);
    printf("%s\n", s2.name);
    printf("%d\n", s2.id);
 
    return 0;
}

单步编译的后可发现 gcc -E test.c -o test.i

typedef struct _tag_Student Student; struct _tag_Student
{
    char* name;
    int id;
};
 
int main()
{
     
    Student s1;
    Student s2;
     
    s1.name = "s1";
    s1.id = 0;
     
    s2.name = "s2";
    s2.id = 1;
     
    printf("%s\n", s1.name);
    printf("%d\n", s1.id);
    printf("%s\n", s2.name);
    printf("%d\n", s2.id);
 
    return 0;
}

posted on 2018-04-27 23:33  arabain  阅读(268)  评论(0)    收藏  举报

导航