Top-Master
Top-Master

Reputation: 8796

What does the "__cplusplus" macro expand to?


Conclusion (added later)

From comments and accepted answer:

Upvotes: 12

Views: 9914

Answers (3)

mtszkw
mtszkw

Reputation: 2783

Yes, it always does expand to numeric value and its meaning is the version of C++ standard that is being used. According to cppreference page, __cplusplus macro should expand to:

  • 199711L (until C++11),
  • 201103L (C++11),
  • 201402L (C++14),
  • 201703L (C++17),
  • 202002L (C++20)
  • 202302L (C++23)

The difference between #if and #ifdef directives is that #ifdef should be used to check whether given macro has been defined to allow a section of code to be compiled.

On the other hand #if (#else, #elif) directives can be used to check whether specified condition is met (just like typical if-condition).

Upvotes: 17

A Fog
A Fog

Reputation: 4608

Unfortunately, the __cplusplus macro has the value 199711 in MS Visual Studio 2022, regardless of the specified C++ standard. Use _MSVC_LANG instead. See VS comment.

This seems to work:

#if defined(_MSVC_LANG)  // MS compiler has different __cplusplus value.
#   if _MSVC_LANG < 201703
#       error Please compile for C++17 or higher
#   endif
#else  // All other compilers.
#   if __cplusplus < 201703
#       error Please compile for C++17 or higher
#   endif
#endif

Upvotes: 1

Hatted Rooster
Hatted Rooster

Reputation: 36503

__cplusplus is required to be defined by the C++ standard. For C++11 or higher __cplusplus > 199711L should hold true.


Does the macro __cplusplus always, even in oldest C++ implementation, contain and expand to a numeric value?

Yes it does.


19.8 C++11

__cplusplus

The integer literal 201703L. [ Note: It is intended that future versions of this International Standard will replace the value of this macro with a greater value. — end note  ]


C++98

__cplusplus The name _ _cplusplus is defined to the value 199711L when compiling a C ++ translation unit. 143)

Upvotes: 3

Related Questions