本文学习自狄泰软件学院 唐佐林老师的 C语言进阶课程,图片全部来源于课程PPT,仅用于个人学习记录
宏定义的本质
实验-字面量比较
#define ERROR -1
#define PATH1 "D:\test\test.c"
#define PATH2 D:\test\test.c
#define PATH3 D:\test\
test.c
int main()
{
int err = ERROR;
char* p1 = PATH1;
//char* p2 = PATH2;//error: 'D' undeclared (first use in this function)|
//char* p3 = PATH3;//error: 'D' undeclared (first use in this function)|
}
宏定义表达式
实验-表达式有效性
#define _SUM_(a, b) (a) + (b)
#define _MIN_(a, b) ((a) < (b) ? (a) : (b))
#define _DIM_(a) sizeof(a)/sizeof(*a)
int main()
{
int a = 1;
int b = 2;
int c[4] = {0};
int s1 = _SUM_(a, b);(a)+(b)
int s2 = _SUM_(a, b) * _SUM_(a, b);//为什么不是9?? (a)+(b)*(a)+(b)=1+2+2
int m = _MIN_(a++, b);// 为啥不是1?? ((a++) < (b) ? (a++) : (b))
int d = _DIM_(c);//求数组大小
printf("s1 = %d\n", s1);
printf("s2 = %d\n", s2);
printf("m = %d\n", m);
printf("d = %d\n", d);
return 0;
}
/*output:
s1 = 3
s2 = 5
m = 2
d = 4
*/
宏的作用域
实验-作用域分析
#include <stdio.h>
void def()
{
#define PI 3.1415926
#define AREA(r) r * r * PI
}
double area(double r)
{
return AREA(r);
}
int main()
{
double r = area(5);
printf("PI = %f\n", PI);
printf("d = 5; a = %f\n", r);
return 0;
}
/*output:
PI = 3.141593
d = 5; a = 78.539815
*/
内置宏
内置宏演示
#include <stdio.h>
#include <malloc.h>
#define MALLOC(type, x) (type*)malloc(sizeof(type)*x)
#define FREE(p) (free(p), p=NULL)
#define LOG(s) printf("[%s] {%s:%d} %s \n", __DATE__, __FILE__, __LINE__, s)
#define FOREACH(i, m) for(i=0; i<m; i++)
#define BEGIN {
#define END }
int main()
{
int x = 0;
int* p = MALLOC(int, 5);
LOG("Begin to run main code...");
FOREACH(x, 5)
BEGIN
p[x] = x;
END
FOREACH(x, 5)
BEGIN
printf("%d\n", p[x]);
END
FREE(p);
LOG("End");
return 0;
}
/*output:
[Apr 4 2024] {D:\Users\cy\Test\test1.c:139} Begin to run main code...
0
1
2
3
4
[Apr 4 2024] {D:\Users\cy\Test\test1.c:153} End
*/
小结
预处理器直接对宏进行文本替换
宏使用时的参数不会进行求值和运算
预处理器不会对宏定义进行语法检查
宏定义时出现的语法错误只能被编译器检测
宏定义的效率高于函数调用
宏的使用会带来一定的副作用