How does the C preprocessor handle circular dependencies?

前端 未结 5 1342
无人共我
无人共我 2021-02-01 11:59

I want to know how the C preprocessor handles circular dependencies (of #defines). This is my program:

#define ONE TWO 
#define TWO THREE
#defi         


        
5条回答
  •  耶瑟儿~
    2021-02-01 12:46

    Here's a nice demonstration of the behavior described in rici's and Eric Lippert's answers, i.e. that a macro name is not re-expanded if it is encountered again while already expanding the same macro.

    Content of test.c:

    #define ONE 1, TWO
    #define TWO 2, THREE
    #define THREE 3, ONE
    
    int foo[] = {
      ONE,
      TWO,
      THREE
    };
    

    Output of gcc -E test.c (excluding initial # 1 ... lines):

    int foo[] = {
      1, 2, 3, ONE,
      2, 3, 1, TWO,
      3, 1, 2, THREE
    };
    

    (I would post this as a comment, but including substantial code blocks in comments is kind of awkward, so I'm making this a Community Wiki answer instead. If you feel it would be better included as part of an existing answer, feel free to copy it and ask me to delete this CW version.)

提交回复
热议问题