C中的宏元编程
循环展开指定的代码段N次
由于宏在展开期间只是简单的字符串替换,不能执行数值计算,因此需要通过递归的方式进行展开。因此当展开层数较多时,需要较多的样板代码。
#include <stdio.h>
#define DECLARE_VARIABLE(n) \
ret = of_property_read_u32(np, "sme,lter" # n, &val); \
if (val == 0 || ret < 0) \
return -EINVAL; \
tc->lter##n = val;
#define EXPAND_VARIABLES_0()
#define EXPAND_VARIABLES_1() DECLARE_VARIABLE(1)
#define EXPAND_VARIABLES_2() DECLARE_VARIABLE(2) EXPAND_VARIABLES_1()
#define EXPAND_VARIABLES_3() DECLARE_VARIABLE(3) EXPAND_VARIABLES_2()
#define EXPAND_VARIABLES_4() DECLARE_VARIABLE(4) EXPAND_VARIABLES_3()
#define EXPAND_VARIABLES(count) EXPAND_VARIABLES_HELPER(count)
#define EXPAND_VARIABLES_HELPER(count) \
EXPAND_VARIABLES_##count()
// Add more EXPAND_VARIABLES_n() definitions as needed
int main() {
EXPAND_VARIABLES(3)
printf("Variables declared successfully.\n");
return 0;
}