2

Summary

1)'#' is used to convert the macro parameter to a string preprocessing period; only valid in the macro definition, and the compiler does not know the existence of'#'

2) You can use #+function name to print the function name when calling

3) '##' for splicing two identifiers pretreatment period; only valid macro definition, compiler does not know the existence of '##' is

4) You can use'##' quickly define a structure, use a structure, and quickly define a class, etc.

·# and ## operator analysis

1、'#'

  • The'#' operator is used to convert the macro parameter to a string preprocessing period double quotation marks to the parameter);
  • '#' Is the conversion is done in the pretreatment period, so only valid macro definition; compiler does not know '#' conversion effect
  • usage:

    #define STRING(s) #s
    printf("%s\n", STRING(hello world));
    
    单步编译:gcc -E test.c -o test.i
    中间结果:printf("%s\n", "hello world");

You can use #+function name to print out the function name when calling :

#define CALL(f, p) (printf("call function: %s\n", #f), f(p))

void func()
{
    printf("function output");
}

int main()
{
    CALL(f, 1);        // C语言中如果不写参数列表,则接受任意多参数
    return 0;
}

2、'##'

  • '##' operator for pretreatment period adhesions two characters ( splice characters)
  • '##' splice role in the pretreatment period is completed, so only valid macro definition, compiler does not know '##' splice action
  • usage:

    #define CONNECT(a, b) a##b
    
    int CONNECR(a, 1);    // int a1;
    a1 = 2;

In the project, you can use '##' to quickly define the structure (define different classes, etc.)

// 在C语言中使用结构体必须带上struct关键字,就可以用下面的宏封装下typedef,
// 然后就可以把struct当成一个类型来用

#define STRUCT(type) typedef strtuct __tag_##type type; \
                        struct __tag_##type
STRTUCT(Student)
{
    char* name;
    int id;
};

int main()
{
    Student s;
    s.name = "ss";
    s.id = 1;

    printf("name: %s, id: %d\n"), s.name, s.id);
    retrun 0;
}

This article is summarized from "C Language Advanced Course" by Tang Zuolin from "Ditai Software Academy".
If there are any errors or omissions, please correct me.


bryson
169 声望12 粉丝