简体   繁体   中英

Why is #undef not working for my function?

I defined something at the beginning:

#define noprint

Then I returned in my functions if it's defined:

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

Then in the main function:

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

And it still doesn't work. How come?

Macros are not variables. They are a simple text replacement tool. If you define, or undefine a macro, then that (un)definition has no effect on the source that precedes the macro. The function definition doesn't change after it has been defined.

Example:

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

After pre-processing has finished, the resulting source looks like this:

void print()
{
    return;
}

main()
{
    print();
}

PS You must give all functions a return type. The return type of main must be int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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