user3600124
user3600124

Reputation: 883

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

Upvotes: 0

Views: 67

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 223872

#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.

Upvotes: 3

Related Questions