Appearance
37 宏与内联函数 · 参数何时求值
宏参数按文本替换;内联函数的形参接收求值后的值。MAX2 在本题选中的分支会再次读取数据。
源码
main.c
c
#include <stdio.h>
#define MAX2(a, b) ((a) > (b) ? (a) : (b))
static unsigned sample(unsigned *counter)
{
return ++*counter;
}
static inline unsigned max2(unsigned a, unsigned b)
{
return a > b ? a : b;
}
int main(void)
{
unsigned reads = 0;
unsigned macro_value = MAX2(sample(&reads), 0u);
reads = 0;
unsigned function_value = max2(sample(&reads), 0u);
printf("%u %u\n", macro_value, function_value);
return 0;
}主机运行
在仓库根目录执行。Windows 可以将输出名写成 reading-37.exe,再从终端运行。
sh
gcc -std=c11 -Wall -Wextra -pedantic examples/c-reading/37/main.c -o reading-37
./reading-37先沿 main() 预测打印结果,再展开核对。
主机输出与手推
text
2 1模拟读数从 1 开始递增。宏比较时读 1,返回时再读出 2;重置后函数只读取 1。
练习
用 gcc -E main.c 查看 main 内的宏展开,再判断哪次读取可以省掉。
验证记录
主机版使用 GCC 编译运行,输出与跟读材料逐项核对。