gpt4 book ai didi

c - 使用#undef 预处理器指令

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

Here are the 2 programs with very minor change.


Practice.c

#include <stdio.h>
#define P (i+j)

main()
{
int i,j,k=0;
printf("\nI = ");
scanf("%d",&i);
printf("\nJ = ");
scanf("%d",&j);
k=P;
printf("\nValue of Defined Macro P = %d\n",k);

#undef P
printf("\nValue of Undefined Macro P = %d\n",k);
}

上述程序的输出是:

I = 5

J = 9

Value of Defined Macro P = 14

Value of Undefined Macro P = 14


New.c

#include <stdio.h>
#define P (i+j)

main()
{
int i,j,k=0;
printf("\nI = ");
scanf("%d",&i);
printf("\nJ = ");
scanf("%d",&j);
k=P;
printf("\nValue of Defined Macro P = %d\n",P);

#undef P
printf("\nValue of Undefined Macro P = %d\n",P);
}

上述程序的输出是:

Practice.c: In function 'main':
Practice.c:15:48: error: 'P' undeclared (first use in this function)
printf("\nValue of Undefined Macro P = %d\n",P);
^
Practice.c:15:48: note: each undeclared identifier is reported only once for eac
h function it appears in


现在我想知道为什么Practice.c编译执行成功了,我用变量k来显示输出,为什么 New.c 直接使用宏模板 P 显示错误?

最佳答案

#define 在编译期间替换代码中的字符串。所以当编译器处理

#define P (i + j),它用 (i + j) 替换它看到的每个 P 实例,直到到达它读取的位置 #undef P。这告诉编译器停止用 (i + j) 替换 P

因此,P 的最后一个实例(在 #undef 语句之后)没有被替换,并且由于上面的代码中没有声明变量 P,它会导致错误。

这在第一个程序中不是问题,因为您已经在行中声明了 k

int i,j,k=0;

关于c - 使用#undef 预处理器指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24339106/

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