c语言 宏

#代表命令要被预处理器处理
#define 定义的宏可以出现在程序的任意位置
#define 定义之后的代码都可以使用这个宏

宏是字面量,不占用内存

单步编译预处理器,只进行文本替换,不进行语法检查:
gcc -E test.c -D test.i

完整编译:
gcc test.c

宏表达式
#define 宏表达式类似于函数
宏表达式被预处理器处理,编译器不知道宏表达式的存在
宏表达式用实参完全替代形参,不进行任何运算
宏表达式没有任何的调用开销
宏表达式中不能出现递归定义

例子:

#include <stdio.h>
#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=3 
int s2 = _SUM_(a, b) * _SUM_(a, b); //a+b*a+b =5 
int m = _MIN_(a++, b); //((a++)<(b)?(a++):(b)) =2 
int d = _DIM_(c); //sizeof(c)/sizeof(*c) 

// printf("s1 = %d
", s1);
// printf("s2 = %d
", s2);
// printf("m = %d
", m);
// printf("d = %d
", d);
return 0;
}

宏的作用域
宏没有作用域限制,因为是由预处理器处理的

内置宏
__FILE__ 被编译的文件名
__LINE__ 当前行号
__DATE__ 编译时的日期
__TIME__ 编译时的时间
__STDC__ 编译器是否遵循标准c规范

code:

#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 
", __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
", p[x]);
END
FREE(p);
LOG("End");
return 0;
}
原文地址:https://www.cnblogs.com/sea-stream/p/10994967.html