gpt4 book ai didi

c - C代码中 `#define`的位置重要吗?

转载 作者:太空宇宙 更新时间:2023-11-04 05:16:55 24 4
gpt4 key购买 nike

我的印象是 #define#include 可以写在我们代码的任何地方,只要它们在预编译时不会产生任何语法错误-处理器在将宏提取到编译器之前处理宏。

我运行了以下代码:

#include <stdio.h>

int main(void) {
int B = A;
#define A 4
printf("%d", B);
return 0;
}

它产生了以下错误:

prog.c: In function 'main': prog.c:4:13: error: 'A' undeclared (first use in this function) int B = A; ^ prog.c:4:13: note: each undeclared identifier is reported only once for each function it appears in

但是当我这样做时,它起作用了!

#include <stdio.h>

int main(void) {
#define A 4
int B = A;
printf("%d", B);
return 0;
}

不确定我在这里遗漏了什么,但为什么编译器会给出这样的错误“undeclared A”?

当预处理器读取 #define A 4 行时,它会开始用 4 替换任何 A 来自后续的代码行

最佳答案

C 文件在预处理阶段和编译阶段都是从上到下解析的。 (注意:正如 MSalters 指出的那样,每个阶段都从顶部单独开始)。

预处理器在看到标记defined 之前不会替换A

Is it so that when pre-processor reads the line #define A 4 it will start replacing any A with 4 from the subsequent lines of code?

是的。你并没有错过太多。

关于c - C代码中 `#define`的位置重要吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41438156/

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