繁体   English   中英

在函数中定义宏值

[英]Define macro value in function

下面两个程序给出不同的结果。 我认为这两个程序应提供与20..20相同的结果,因为宏定义位于fun()中,而不应该影响fun()之外。 你能解释原因吗?

答:结果是20..20

# include <stdio.h>
# define i 20
void fun();
main()
{
    printf("%d..", i);
    fun();
    printf("%d", i);
}

void fun()
{
    #undef i 
    #define i 30 
}

B:结果是30..30

# include <stdio.h>
# define i 20

void fun()
{
#undef i 
#define i 30 
}

main()
{
    printf("%d..", i);
    fun();
    printf("%d", i);
}

C预处理程序不是编译器的一部分,而是编译过程中的单独步骤。

现在,由于这是编译过程中的一个单独步骤,因此与为i分配不同的值不同。 当您的代码运行时,它将i视为20因为它是在main之前定义的。 但是,正如我说,这是一个单独的步骤, 并且它不关心的功能范围,所以,有前主i=20 )和之后主要i=30 )。 当预处理器运行时,它将整个范围视为全局范围。

尝试在主体而不是函数中使用#define ,然后检查会发生什么...

例:

void f(){
    #define a 5
    printf("%d\n", a);
    #undef a
    #define a 10
    printf("%d\n", a);
}

int main()
{
    printf("%d\n", a); // a can be printed even though f() was never called!!
    #define i 20
    printf("%d\n", i); // 20
    #undef i
    #define i 30
    printf("%d\n", i); // 30! :)
    return 0;
}

您可以在此问答中找到更多信息

定义在编译之前已进行了预处理,并且它们是全局的。 如果要在函数中分配值,只需使用常规C分配运算符和全局变量即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM