Home > front end >  Why is #undef not working for my function?
Why is #undef not working for my function?

Time:12-01

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?

CodePudding user response:

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

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

  • Related