根据特定值多次调用#define
Call #define multiple times based on a specific value
如果你在 C:
中调用这样的东西
#include <stdio.h>
#define REPS ,a
...
int a = 1;
printf("%d" REPS);
它会工作,但是是否可以根据未知值多次调用 REPS
宏,例如,我想在 scanf
中有五个输入,但是我希望我的代码自动执行它(例如,如果 #define REPS ,a[i]
那么:... ,a[1] ,a[2]
)?
It will work, but is it possible to call the REPS multiple times based in an unknown value
No. #define
创建一个预处理器宏,你可以在你的代码中使用它,但是当编译器编译你的代码时,实际值被替换为宏.如果你有:
#define FOO 7
例如,那么在编译代码之前,代码中出现的每个 FOO
都会被替换为 7
;当编译器看到你的代码时,没有 #define
也没有 FOO
,只有 7
FOO
在哪里。尽管还有一些其他预处理器命令(例如 #if
)可以控制是否对给定的 #define
进行求值,但没有其他预处理器控制结构(循环等)。
I want to have five inputs in a scanf, yet I want my code to automate it (for example, if #define REPS ,a[i] then: ... ,a[1] ,a[2])?
你当然可以自动化这样的事情;只是预处理器不是完成这项工作的正确工具。考虑:
int reps = 5
//...
for (int i = 0; i < reps; i++) {
scanf(" %d", &a[i]);
}
REPS 在编译时求值,因此在本例 a
中它不能依赖于 运行 时间值。有 hack,但通常你不能用宏进行编译循环。
我建议您改为按照以下行编写一个函数:
#include <stdio.h>
void print_int_array(size_t n, int a[n]) {
for(int i = 0; i < n; i++)
printf("%d%s", a[i], i + 1 < n ? ", " : "\n");
}
int main() {
print_int_array(0, (int []) {});
print_int_array(1, (int []) {1});
print_int_array(2, (int []) {1, 2});
}
如果你在 C:
中调用这样的东西#include <stdio.h>
#define REPS ,a
...
int a = 1;
printf("%d" REPS);
它会工作,但是是否可以根据未知值多次调用 REPS
宏,例如,我想在 scanf
中有五个输入,但是我希望我的代码自动执行它(例如,如果 #define REPS ,a[i]
那么:... ,a[1] ,a[2]
)?
It will work, but is it possible to call the REPS multiple times based in an unknown value
No. #define
创建一个预处理器宏,你可以在你的代码中使用它,但是当编译器编译你的代码时,实际值被替换为宏.如果你有:
#define FOO 7
例如,那么在编译代码之前,代码中出现的每个 FOO
都会被替换为 7
;当编译器看到你的代码时,没有 #define
也没有 FOO
,只有 7
FOO
在哪里。尽管还有一些其他预处理器命令(例如 #if
)可以控制是否对给定的 #define
进行求值,但没有其他预处理器控制结构(循环等)。
I want to have five inputs in a scanf, yet I want my code to automate it (for example, if #define REPS ,a[i] then: ... ,a[1] ,a[2])?
你当然可以自动化这样的事情;只是预处理器不是完成这项工作的正确工具。考虑:
int reps = 5
//...
for (int i = 0; i < reps; i++) {
scanf(" %d", &a[i]);
}
REPS 在编译时求值,因此在本例 a
中它不能依赖于 运行 时间值。有 hack,但通常你不能用宏进行编译循环。
我建议您改为按照以下行编写一个函数:
#include <stdio.h>
void print_int_array(size_t n, int a[n]) {
for(int i = 0; i < n; i++)
printf("%d%s", a[i], i + 1 < n ? ", " : "\n");
}
int main() {
print_int_array(0, (int []) {});
print_int_array(1, (int []) {1});
print_int_array(2, (int []) {1, 2});
}