有趣的:扩展 C 预处理器
Fun Extending the C Preprocessor

原始链接: https://www.davidpriver.com/Fun-Extending-the-C-Preprocessor.html

这个 C 代码片段定义了一个预处理器 MAP 工具:`__map` 统计其可变参数并分派到 `MAP_n`,后者递归地将宏应用于每个参数。`PRINTINT` 将每个参数展开为 `printf` 调用,打印其文本形式和整数值。在 `main` 中,`__map(PRINTINT, 1,2,3,4,x,y,z)` 生成七条 `printf` 调用,显示如 `1 = 1`、`x = 1` 和 `z = 3` 的值。

``` Hacker News 新 | 过往 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 有趣地扩展 C 预处理器 ( davidpriver.com ) 7 分 由 david2ndaccount 2 小时前 | 隐藏 | 过往 | 收藏 | 2 条评论 帮助 pajko 12 分钟前 [–] 你不需要扩展预处理器就能拥有 MAP: https://github.com/swansontec/map-macro 回复 david2ndaccount 11 分钟前 | 父评论 [–] 文章展示了如何实现 map,但它本应是内置的 回复 考虑申请 YC 的 2027 冬季批次! 申请 截止 11 月 2 日。 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索: ```
相关文章

原文
// map.c
#define CAT(a, b) CAT_(a, b)
#define CAT_(a, b) a##b
#define NARG(...) \
  NARG_(__VA_ARGS__ __VA_OPT__(,) 8,7,6,5,4,3,2,1,0)
#define NARG_(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define MAP_0(m)
#define MAP_1(m, x)      m(x)
#define MAP_2(m, x, ...) m(x) MAP_1(m, __VA_ARGS__)
#define MAP_3(m, x, ...) m(x) MAP_2(m, __VA_ARGS__)
#define MAP_4(m, x, ...) m(x) MAP_3(m, __VA_ARGS__)
#define MAP_5(m, x, ...) m(x) MAP_4(m, __VA_ARGS__)
#define MAP_6(m, x, ...) m(x) MAP_5(m, __VA_ARGS__)
#define MAP_7(m, x, ...) m(x) MAP_6(m, __VA_ARGS__)
#define MAP_8(m, x, ...) m(x) MAP_7(m, __VA_ARGS__)
#define __map(m, ...) \
  CAT(MAP_, NARG(__VA_ARGS__))(m __VA_OPT__(,) __VA_ARGS__)
int x = 1;
int y = 2;
int z = 3;

#define PRINTINT(x) printf(#x " = %d\n", x);
int printf(const char*, ...);
int main(){
    __map(PRINTINT, 1, 2, 3, 4, x, y, z)
}
// map.i
int x = 1;
int y = 2;
int z = 3;
int printf(const char*, ...);
int main(){
    printf("1" " = %d\n", 1); // 1 = 1
    printf("2" " = %d\n", 2); // 2 = 2
    printf("3" " = %d\n", 3); // 3 = 3
    printf("4" " = %d\n", 4); // 4 = 4
    printf("x" " = %d\n", x); // x = 1
    printf("y" " = %d\n", y); // y = 2
    printf("z" " = %d\n", z); // z = 3
}
联系我们 contact @ memedata.com