【C】25.# 和 ## 操作符使用分析

# 介绍

#include <stdio.h>

#define STRING(x) #x

int main()
{
    
    printf("%s\n", STRING(Hello world!));
    printf("%s\n", STRING(100));
    printf("%s\n", STRING(while));
    printf("%s\n", STRING(return));

    return 0;
}

输出结果:

预编译处理结果:

int main()
{

    printf("%s\n", "Hello world!");
    printf("%s\n", "100");
    printf("%s\n", "while");
    printf("%s\n", "return");

    return 0;
}

实际开发应用:

在C开发中没法知道调用的函数的函数名,利用 # 的妙用可以知道函数被调用

#include <stdio.h>

#define CALL(f, p) (printf("Call function %s\n", #f), f(p))
   
int square(int n)
{
    return n * n;
}

int func(int x)
{
    return x;
}

int main()
{
    int result = 0;
    
    result = CALL(square, 4);
    
    printf("result = %d\n", result);
    
    result = CALL(func, 10);
    
    printf("result = %d\n", result);

    return 0;
}

运行结果:

call function square
result = 16
call function func
result = 10

## 的介绍

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;
}

运行结果

1
2

预编译处理结果:

int main()
{

    int name1;
    int name2;

    name1 = 1;
    name2 = 2;

    printf("%d\n", name1);
    printf("%d\n", name2);

    return 0;
}

工程实际应用:

可以利用这样的特性,简写代码中的结构体,简化代码。

//#include <stdio.h>

#define NAME(n) name##n

#define STRUCT(type)  typedef struct _tag_##type  type; \
                              struct _tag_##type 

STRUCT(Student)
{
   char* name;
   int id;
};

STRUCT(book)
{
   int data;
   int price;

};

int main()
{

   Student s1;

   s1.id = 10;
   s1.name = "kevin";
   return 0;

}

预编译处理结果:

typedef struct _tag_Student Student; 
struct _tag_Student
{
   char* name;
   int id;
};

typedef struct _tag_book book; 
struct _tag_book
{
   int data;
   int price;

};

小结:

发布了84 篇原创文章 · 获赞 0 · 访问量 761

猜你喜欢

转载自blog.csdn.net/zhabin0607/article/details/103312116