Search code examples
c++c-preprocessoroperator-precedence

Does order matter when #defines are using other #defines?


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?


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;
    }