当#defines正在使用其他#defines时,顺序是否重要?

Lud*_*wik 24 c++ operator-precedence c-preprocessor

根据这个问题的答案,以下代码是合法的:

#define three 3
#define nine three*3

int main()
{
    std::cout << nine;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当然,它编译并运行良好.但是,上述问题的答案还指出,应该注意这些#define指令的顺序,并且#define应该在它们之前定义将在其他s中使用的指令.但是以下代码:

#define nine three*3
#define three 3

int main()
{
    std::cout << nine;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译并运行良好,并打印"9".

我的编译器是否让我轻松,或者订单确实与使用其他#defines的#defines无关?编译是否会在更复杂的项目中失败?

值得一提的是,上述问题涉及C,而我的代码是C++.这是(假设的)行为差异的来源吗?

Yan*_*kes 8

three宏只需要在使用nine宏之前定义.您甚至可以three在每次使用之前进行更改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;
}
Run Code Online (Sandbox Code Playgroud)


pol*_*ket 7

预处理器执行多次运行,并且仅在未找到所有定义的其他匹配项时才完成。因此,您的代码示例都可以工作,但预处理器需要再运行一次,以防发生第二次运行。您必须小心递归定义。然后 ppc 将永远不会退出。

  • 你不能让预处理器进行无限循环。当他发现与之前展开的标记相同时,他停了下来。例如。`#define Foo Foo` 结果为 `Foo`。 (3认同)