0

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?

  • 4
    `#define` is just textual substitution. Your definition of `print()` will have whatever the result is of performing those substitutions. When you invoke it in `main`, it uses that definition. It doesn't go back and recompile the definition of `print()` based on what it _would be_ if you'd defined things differently earlier on. – Nathan Pierson Nov 30 '21 at 23:47

1 Answers1

2

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Yeah I have return 0 for main but I leave it out of the post because I never make it return anything else and it's implicit –  Nov 30 '21 at 23:54
  • 1
    @PupperGump `main` is special in that you don't need a return statement. But you must declare the return type for all functions. – eerorika Dec 01 '21 at 00:32
  • Oh yeah I got that. If I don't the compiler warns me anyways. –  Dec 01 '21 at 00:45