一、预定义符号
二、#define
1.#define定义标识符
#define + 自定义名称 + 代替的内容
例:
#define MAX 100
#define CASE break;case
#define CASE break;case
int main()
{
int n = 0;
switch (n)
{
case 1:
CASE 2:
CASE 3:
CASE 4:
}
return 0;
}
这里的CASE 代替了 break;case 为了避免break的遗忘
2.#define定义宏
#define MAX(x,y) ((x)>(y)?(x):(y))
#define M 2
int main()
{
int m = MAX(M, 3);
return 0;
}
3.#define 的替换规则
4.#和##的应用
使用#,把一个宏参数变成对应字符串
#define PRINT(formate,x) printf("the value of "#x" is "formate"\n",x)
int main()
{
int a = 10;
PRINT("%d", a);
float c = 3.14f;
PRINT("%f", c);
return 0;
}
##把位于两边的符号合成一个符号
#define CAT(x,y) x##y
int main()
{
int ab = 2025;
printf("%d\n", CAT(a, b));
return 0;
}
输出:2025
5.宏与函数相比
(1)宏的优点:
(2)宏的缺点:
三、#undef
用于移除一个宏定义
例:#undef MAX
四、条件编译
1.进行选择性的编译代码
# if 常量表达式
#elif 常量表达式
#else
……
#endif
#define M 5
int main()
{
#if M==1;
printf("hehe\n");
#elif M==5;
printf("haha\n");
#else
printf("heihei\n");
#endif
return 0;
}
输出:haha
2.判断是否被定义
#define MAX 100
int main()
{
#if defined(MAX);
//也可以写成
//#ifdef(MAX);
printf("haha\n");
#endif
return 0;
}
输出:haha
3.解决头文件被多次包含问题
两种方法来解决
//方法一
#ifndef __TEST_H__
#define __TEST_H__
//头文件内容
#endif
//方法二
#pragma once