Search code examples
c++precompileundef

weird behavior of #undef


#include <iostream>

#define MY_CONST 10

#define MY_OTHER_CONST MY_CONST

#undef MY_CONST

int main() {

  enum my_enum : int {

    MY_CONST = 100
  };

  std::cout << MY_OTHER_CONST;

  return 0;

}

I would expect 10 as an output, but this program outputs 100. Can someone explain what is going on here?

https://godbolt.org/z/77EedG11x


Solution

  • #define MY_OTHER_CONST MY_CONST defines the macro MY_OTHER_CONST to have a replacement list of MY_CONST. No replacement is performed when defining a macro.

    In std::cout << MY_OTHER_CONST;, MY_OTHER_CONST is replaced by its replacement list, becoming MY_CONST. At this point, there is no macro definition for MY_CONST, so no further replacement is performed. Then MY_CONST refers to the enum constant MY_CONST, which has value 100.