Question

According to the answer to this question, the following code is legit:

#define three 3
#define nine three*3

int main()
{
    std::cout << nine;
    return 0;
}

And sure, it compiles and runs fine. However, the answer to mentioned question also states that one should be careful about the order of such #define directives, and one that will be used in other #defines should be defined before them. But the following code:

#define nine three*3
#define three 3

int main()
{
    std::cout << nine;
    return 0;
}

Also compiles and runs fine, and it prints "9".

Is my compiler letting me off easy, or does the order indeed not matter with #defines that use other #defines? Would the compilation fail on a more complicated project?

One thing worth mentioning is that the mentioned question speaks of C, whilst my code is in C++. Is that where the (supposed) differences in behavior come from?

Was it helpful?

Solution

three macro need be only defined before use of nine macro. You can even change three before every use of nine:

#define nine three*3
#define three 3

int main()
{
    std::cout << nine; //9
#undef three
#define three 4
    std::cout << nine; //12
#undef three
    //no `three` macro defined here
    int three = 2;
    std::cout << nine; //three * 3 == 6
    return 0;
}

OTHER TIPS

The preprocessor does multiple runs and only finishes when no other occurrences of all defines are found. Thus, your code samples both work but the preprocessor needs one more run in case of the second one. You have to be careful with recursive defines. The ppc then would never exit.

This steps would be done in the preprocessor step and all literals would be replaced with their value. This can be verified if we compile with the option:

$ g++ -save-temps basic.cpp -o out

This is the output after preprocessor step(basic.ii file):

int main()
{
    std::cout << 3*3;
    return 0;
}

for your sample program. So order should not be matter as it is kind of find and replace and it is getting done prior to actual compilation of the program.

Actually it is because of two step parser. In first step it tries to resolve all the symbol and in second step actual value is placed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top