Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "__cplusplus" macro expand to?

Tags:

c++

c++11

macros

  • What does the C++ macro __cplusplus contain and expand to?

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

  • Is it safe to use #if __cplusplus or should we use instead of that #ifdef __cplusplus?


Conclusion (added later)

From comments and accepted answer:

  • __cplusplus expands to a number representing the standard's version, except pre-standard C++ in the early 90s (which simply expanded to 1).

  • Yes, even in oldest C++ implementation (expands to a numeric value).

  • No, #ifdef should be used when header is shared with C-language (because some C-compilers will warn when #if checks undefined macro).

like image 419
Top-Master Avatar asked Apr 19 '18 07:04

Top-Master


People also ask

What is __ cplusplus macro?

__cplusplus. This macro is defined when the C++ compiler is in use. You can use __cplusplus to test whether a header is compiled by a C compiler or a C++ compiler. This macro is similar to __STDC_VERSION__ , in that it expands to a version number.

What is __ function __ in C++?

(C++11) The predefined identifier __func__ is implicitly defined as a string that contains the unqualified and unadorned name of the enclosing function. __func__ is mandated by the C++ standard and is not a Microsoft extension.

What is __ LINE __ in C?

__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.

Why macro is used in C++?

So, macros not only make names shorter, and infact typedefs and ref alias can also be used to make names shorter, but macros can also avoid runtime overheads. Macros happen way before runtime. Macros have been avoiding run time over heads way before CPP features such as move and template.


1 Answers

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)

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

like image 99
mtszkw Avatar answered Sep 20 '22 03:09

mtszkw