#和##运算符使用解析

编译预处理

专题三:编译预处理。包括以下章节:

  • 编译过程简介
  • 宏定义与宏使用分析
  • 条件编译使用分析
  • #error和#line
  • #pragma预处理分析
  • #和##运算符使用解析

#运算符

  • #运算符用于预编译期将宏参数转换为字符串

6-1.c

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

6-1.i

# 1 "6-1.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "6-1.c"

/*......省略n行......*/

# 943 "/usr/include/stdio.h" 3 4

# 9 "6-1.c" 2



int main()
{

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

    return 0;
}

实例分析6-1

6-2.c

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

结果:
这里写图片描述

##运算符

  • ##运算符用于预编译期粘连两个符号

6-3.c

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

6-3.i

# 1 "6-3.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "6-3.c"

/*......省略n行......*/

# 943 "/usr/include/stdio.h" 3 4

# 2 "6-3.c" 2

int main()
{

    int name1;
    int name2;

    name1 = 1;
    name2 = 2;

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

    return 0;
}

结果:
这里写图片描述

实例分析6-2

6-4.c

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

6-4.i

# 1 "6-4.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "6-4.c"

/*......省略n行......*/

# 943 "/usr/include/stdio.h" 3 4

# 2 "6-4.c" 2

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

结果:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值