0

我在一开始就定义了一些东西:

#define noprint

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

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

然后在主函数中:

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

它仍然不起作用。怎么来的?

4

1 回答 1

2

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

例子:

#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();
}

PS 你必须给所有函数一个返回类型。的返回类型main必须是int

于 2021-11-30T23:47:15.767 回答