为什么#undef 不适用于我的函数?

Why is #undef not working for my function?

开头我定义了一些东西:

#define noprint

然后我返回我的函数,如果它被定义:

void print()
{
    #ifdef noprint
        return;
    #else
        //do stuff
    #endif
}

然后在main函数中:

main()
{
    #undef noprint
    print();
}

而且还是不行。怎么会?

宏不是变量。它们是一个简单的文本替换工具。如果您定义或取消定义宏,则该(取消)定义对宏之前的源代码没有影响。函数定义定义后不改变

示例:

#define noprint
// noprint is defined after the line above

void print()
{
    #ifdef noprint // this is true because noprint is defined
        return;
    #else
        //do stuff
    #endif
}

main()
{
    #undef noprint
// noprint is no longer after the line above
    print();
}

预处理完成后,生成的源代码如下所示:

void print()
{
    return;
}

main()
{
    print();
}

P.S。您必须为所有函数提供 return 类型。 main 的 return 类型必须是 int.