c++macros

why macro recursive stop condition not work?


I define some macro:

#define CAT(A, B) A##B
#define AA(a, b) CAT(a, b)
#define YYY(a, b) CAT(a, b)

Can someone explain why the result of the second one is ab

CAT(A, A(a, b)) 
  -> AA(a, b)
  -> CAT(a, b)

YYY(A, A(a, b))
  -> CAT(A, A(a, b))
  -> AA(a, b)
  -> CAT(a, b)
  -> ab // why

Solution

  • By default, Microsoft's C++ compiler (MSVC) uses its legacy preprocessor, reportedly "based on character buffers rather than preprocessor tokens".

    However, starting in Visual Studio 2019 version 16.5, there is the /Zc:preprocessor compiler switch you can use to enable the standards-conforming preprocessor. Open the project's configuration properties, and under the "C/C++" section, on the "Preprocessor" property page, change the "Use Standard Conforming Preprocessor" property to "Yes".

    The "MSVC new preprocessor overview" article even has a relevant example under the "Rescanning replacement list for macros" section, explaining and comparing the old vs new preprocessor behaviors while demonstrating an issue similar to the one you are facing in your question.