Home > Back-end >  Why replace an existing keyword in C/C with a macro?
Why replace an existing keyword in C/C with a macro?

Time:10-16

I often come across keywords or one-word identifiers defined with another name. For example, boost defines noexcept as BOOST_NOEXCEPT, some C standard libraries replace [[nodiscard]] with _NODISCARD, Windows API is prone to introduce their own macros as well, and so forth. I didn't really manage to find anything which would explain this.

This makes an unfamiliar person search for what such macros mean which therefore makes the code a bit harder to understand (at least this is how I see it). Why is such tendency so widespread? What is the purpose of replacing existing one-word constructs with macros?

CodePudding user response:

The most useful case of these is when you target both compilers that support a new feature and ones that do not.
For instance:

#if CompilerSupportsNoexcept
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif

CodePudding user response:

This may be used in different scenarios for flexibility and code clarity. Following cases come in mind:

  • support for different compilers, which implements the same feature in a different way or do not support at all
  • support for different build options, i.e. building static vs dynamic library
  • support for different OSes (functions, exported by dynamic libraries, in Windows and Linux would have different signatures.
  • Debug vs Release builds
  • Related