C语言宏定义 #

一、简单宏 #

1.1 定义常量 #

c
#define PI 3.14159
#define MAX_SIZE 100
#define NEWLINE '\n'

1.2 使用示例 #

c
#include <stdio.h>

#define PI 3.14159

int main() {
    double area = PI * 5 * 5;
    printf("面积: %.2f\n", area);
    return 0;
}

二、带参数宏 #

2.1 定义 #

c
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define SQUARE(x) ((x) * (x))

2.2 使用示例 #

c
#include <stdio.h>

#define MAX(a, b) ((a) > (b) ? (a) : (b))

int main() {
    printf("最大值: %d\n", MAX(10, 20));
    return 0;
}

2.3 注意括号 #

c
#define SQUARE(x) x * x

int result = SQUARE(1 + 2);

展开为 1 + 2 * 1 + 2 = 5,不是预期的9。

正确写法:

c
#define SQUARE(x) ((x) * (x))

三、多行宏 #

c
#define SWAP(a, b, type) \
    do { \
        type temp = a; \
        a = b; \
        b = temp; \
    } while (0)

四、宏与函数对比 #

特性 函数
类型检查
执行速度 较慢
代码大小 可能增大 不变
调试 困难 容易

五、总结 #

要点 说明
括号 参数加括号
副作用 注意++等操作
多行 使用\续行

下一步,让我们学习条件编译!

最后更新:2026-03-26