gpt4 book ai didi

根据特定值多次调用#define

转载 作者:行者123 更新时间:2023-12-04 17:08:24 26 4
gpt4 key购买 nike

如果你在 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

否。 #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]);
}

关于根据特定值多次调用#define,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70015899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com