c - 这两段代码的工作

标签 c c-preprocessor

<分区>

这里有两段C代码,但我不明白它们是如何工作的:

程序 1:

#include<stdio.h>
#define s 10
fun() {
 #undef s
 #define s 20
}
int main(){
 printf("%d\n",s);
 fun();
 printf("%d\n",s);
 return 0;
}
Output: 20
        20

程序 2:

#include<stdio.h>
#define s 10
int main(){
 printf("%d\n",s);
 fun();
 printf("%d\n",s);
 return 0;
}
fun() {
 #undef s
 #define s 20
}
output: 10
        10

我所知道的是预处理器在 main() 开始之前工作并替换它的所有变量。 这里 fun() 在一个 printf() 之后被调用,所以两个程序如何通过改变 fun() 的位置输出不同的值?

最佳答案

宏将在编译时被替换。所以预处理后的代码将是这样的,

案例一:

#include<stdio.h>

fun() {
}
int main(){
 printf("%d\n", 20);//latest definition of s will be considered.
 fun();
 printf("%d\n",20);
 return 0;
}

案例二:

#include<stdio.h>

int main(){
 printf("%d\n",10); //replaced with 10 only, because in this instance, there is no change in s 
 fun();
 printf("%d\n",10);
 return 0;
}
fun() {
 //#undef s
 //#define s 20 //no use in ur code. 
}

fun_extra() { //Added for demo
   printf("%d\n",s);//will be replaced by 20. 
}

关于c - 这两段代码的工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18223146/

相关文章:

c/c++ 加入进程?

c - 当依赖 DLL 丢失时,尝试使用 LoadLibrary 在 Windows 上加载 DLL

python - 使用 Python 制作预处理器

visual-studio - Visual Studio #if on Visual Studio 版本

保留换行符的 C++ 预处理器字符串化?

python - 使用 ctypes 加载 .dll

c - 在windows上编译socket proram时mingw出错

c - while(1) 的目的; C语句

c# - MVC 助手扩展问题

c - 有没有一种方法可以同时检查宏是否已定义并且它等于某个值