Q:

C++ Macros #ifdef

void testFunc();

int myval = 0;

int main()
{
    int a = 1;

    if (a > 0)
    {
        #define TEST1
        testFunc();
        #undef TEST1
    }

    int b = 2;
    if ( b > 0)
    {
        #define TEST2
        testFunc();
        #undef TEST2
    }

    std::cout << "val : " << myval << endl;

    getchar();

    return 0;
}

void testFunc()
{

#ifdef TEST1
#define HERE 1
#endif

#ifdef TEST2
#define HERE 2
#endif

#ifdef HERE
    myval = HERE;
#else
    myval = -1;
#endif

}

How can I print the value of HERE to be 1 when testFunc() is called first time and then print the value of HERE to be 2 when it is called second time.
With the current code that I have, the value that is being printed is -1.

A:

What you're missing is that the preprocessor directives evaluate before compile time.
That means that as the preprocessor parses your code it:

Sets TEST1
Unsets TEST1
Sets TEST2
Unsets TEST2
Checks if TEST1 is defined (it isn't)
Checks if TEST2 is defined (it isn't)
Checks if HERE is defined (it isn't)

That means testFunc becomes:
void testFunc() {
    myval = -1;
}

And then, after this preprocessing, your code is compiled.
I would consider using something other than the preprocessor to accomplish what you are trying to achieve.

