L20#和##使用

L20#和##使用

1. #


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

作用: #在宏定义中将后面的任何元素转换为一个字符串

2. ##

作用: ##用于在预编译期粘连两个符号
范例:结构体定义


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

猜你喜欢

转载自blog.csdn.net/shouzhoudd/article/details/46352265