【发布时间】:2014-01-15 11:49:49
【问题描述】:
例如,这里有一个 C 常见的#define:
#define USERNAME_LEN 100
#define SCAN_FMT "%100s"
// str is input from somewhere
char username[USERNAME_LEN + 1];
ret = sscanf(str, SCAN_FMT, username);
// check ret == 1 ?
我们可以有类似的东西吗:
#define SCAN_FMT "%" USERNAME_LEN "s"
当然,这个语法不是我们想要的,而是终极目标 就是将数字#define混合成字符串#define
注意:我知道我们可以这样做:
sprintf(SCAN_FMT, "%%ds", USERNAME_LEN); // char SCAN_FMT[10];
但这不是我想要的,因为它需要运行时生成, 最好是基于 ANSI-C 或 std99。
【问题讨论】:
-
这个答案可能对你有帮助:stackoverflow.com/a/20642870/694576
标签: c constants c-preprocessor