预处理

2023/7/20 c

# 宏定义

# 不带参数的宏定义

#include <stdio.h>

// 不带参宏定义
#define PI 3.14159
#define STANDARD "hello world"

int main() {
    printf("PI=%f\n",PI);     // PI=3.14159
    printf("2PI=%f\n",PI*2);  // 2PI=6.283180
    printf(STANDARD);         // hello world
    return 0;
}

# 带参数的宏定义

#include <stdio.h>

// 带参宏定义
#define MIX(a,b) ((a)*(b)+(b))

int main() {
    int result = MIX(5,9);
    printf("result=%d",result); // result=54
    return 0;
}
int result = MIX(5,9);
// 会被替换为
int result = ((5)*(9)+(9));

# 宏定义的注意事项

如果不带括号结果可能不是想要的结果

#include <stdio.h>

// 带参宏定义
#define MIX(a,b) (a*b+b)

int main() {
    int result1 = MIX(5,9);
    int result2 = MIX(5,4+5);
    printf("result1=%d\n",result1); // result=54
    printf("result2=%d\n",result2); // result=34
    return 0;
}
int result2 = MIX(5,4+5);
// 会被替换为
int result2 = (5*4+5+4+5);

# 条件编译

# #if 命令

示例一: if 命令

#include <stdio.h>
#define NUM 50

int main() {
    int i = 0;

    #if NUM>50
        i++;
    #endif
    #if NUM==50
        i = i + 50;
    #endif
    #if NUM<50
        i--;
    #endif
    printf("i=%d",i);
    return 0;
}

示例二:if else 命令

#include <stdio.h>
#define NUM (-2)

int main() {
    #if NUM>0
        printf("NUM大于0");
    #else
        #if NUM<0
            printf("NUM小于0");
        #else
             printf("NUM等于0");
        #endif
    #endif
    return 0;
}

示例三: elif(相当于 else if) 命令

#include <stdio.h>
#define NUM 50

int main() {
    int i = 0;

    #if NUM>50
        i++;
    #elif NUM==50
        i = i + 50;
    #else
        i--;
    #endif
    printf("i=%d",i);
    return 0;
}

# #ifdef 及#ifndef 命令

#ifdef:如果宏已经定义,则对后面的代码进行编译

#ifndef:如果宏没有定义,则对后面的代码进行编译

#include <stdio.h>
#define A "AA"

int main() {
    #ifdef A
        printf("A被定义了\n");
    #endif

    #ifndef B
        printf("B没有被定义\n");
    #endif
    return 0;
}

输出

A被定义了
B没有被定义

# #undef 命令

1.使用#undef 命令可以删除事先定义好的宏定义

2.使用#undef 命令可将宏名限制在特定的代码段中

#define MAX_SIZE 100
char array[MAX_SIZE];
#undef MAX_SIZE

# #line 命令

#line 命令可以修改编译器的行号指示器,使其显示指定的行号和文件名

#line 行号["文件名"]
#line 5 "main.c"
#include <stdio.h> // 第5行
// 第6行
int main() { // 第7行
    printf("当前行号:%d\n",__LINE__); // 当前行号:8
    printf("当前行号:%d\n",__LINE__); // 当前行号:9
    return 0;
}