cvisual-studio-2008c-preprocessorpreprocessor-directive

#define, #ifdef #undef #endif


I have the following code

#define PROC_ADD

void main(void)
{
    while(1)
    {
#ifdef PROC_ADD
// Do this code here then undefined it to run the code in the else
// processing work
#undef PROC_ADD
#else
// now that PROC_ADD has been undefined run this code
// processing work
#endif
    }
}

However, it will run the code. But it won't run the code in the else after the PROC_ADD has been undefined.

I think the reason could be that you can only define and undefine at compile time, and not at run-time. However, I am not really sure.


Solution

  • You are doing the build time equivalent of:

    int x = 1;
    
    int main()
    {
        if (x)
        {
            ...
            x = 0;
        }
        else
        {
            ...
        }
    }
    

    ifdef, etc. happen at build time, but for your example, that's not an issue. Once you evaluate the if (either the runtime or build-time form), the decision about which branch to take it made. Changing something after the decision has been made does not change that decision.