Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#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.

like image 535
ant2009 Avatar asked Jun 20 '26 23:06

ant2009


1 Answers

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.

like image 145
R Samuel Klatchko Avatar answered Jun 22 '26 12:06

R Samuel Klatchko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!