1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include <stdio.h>
#define REPEAT_1(x) x #define REPEAT_2(x) REPEAT_1(x) REPEAT_1(x) #define REPEAT_4(x) REPEAT_2(x) REPEAT_2(x) #define REPEAT_8(x) REPEAT_4(x) REPEAT_4(x)
#define COUNT_ARGS_IMPL(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,N,...) N #define COUNT_ARGS(...) COUNT_ARGS_IMPL(__VA_ARGS__,10,9,8,7,6,5,4,3,2,1,0)
#define IF_ELSE(condition, true_val, false_val) \ IF_ELSE_IMPL(condition, true_val, false_val) #define IF_ELSE_IMPL(condition, true_val, false_val) \ IF_ELSE_##condition(true_val, false_val) #define IF_ELSE_0(true_val, false_val) false_val #define IF_ELSE_1(true_val, false_val) true_val
#define SAFE_MAX(a, b) ({ \ typeof(a) _a = (a); \ typeof(b) _b = (b); \ (_a > _b) ? _a : _b; \ })
void advancedMacroTricks() { printf("\n=== 高级宏技巧 ===\n"); printf("重复宏测试:"); REPEAT_4(printf("* ")); printf("\n"); printf("参数个数测试:\n"); printf("COUNT_ARGS(a) = %d\n", COUNT_ARGS(a)); printf("COUNT_ARGS(a,b,c) = %d\n", COUNT_ARGS(a,b,c)); printf("COUNT_ARGS(1,2,3,4,5) = %d\n", COUNT_ARGS(1,2,3,4,5)); printf("\n条件宏测试:\n"); printf("IF_ELSE(1, \"true\", \"false\") = %s\n", IF_ELSE(1, "true", "false")); printf("IF_ELSE(0, \"true\", \"false\") = %s\n", IF_ELSE(0, "true", "false")); #ifdef __GNUC__ int x = 10, y = 20; float a = 3.14f, b = 2.71f; printf("\n类型安全宏测试:\n"); printf("SAFE_MAX(%d, %d) = %d\n", x, y, SAFE_MAX(x, y)); printf("SAFE_MAX(%.2f, %.2f) = %.2f\n", a, b, SAFE_MAX(a, b)); #endif }
|