I defined some code in c++, ex:
#define array_width 3;
Visual Studio will suggest changing to:
constexpr auto array_width = 3;
what's the reason to change? and what is the benefit?
Thanks.
I defined some code in c++, ex:
#define array_width 3;
Visual Studio will suggest changing to:
constexpr auto array_width = 3;
what's the reason to change? and what is the benefit?
Thanks.
The main reason for these suggestions is that the preprocessor does nothing but simple textual replacement (no type checking or similar things a compiler performs). There are many potential pitfalls when using the preprocessor - when you can avoid it, do so. `constexpr´ is one of the building blocks that allow for fewer macros these days.
To back this with an authority: From S. Meyers, Effective C++, Item 2 ("Prefer const
s, enum
s, and inline
s to #define
s"):
Things to Remember
- For simple constants, prefer
const
objects orenum
s to#define
s- [...]
From S. Meyers, Effective Modern C++, Item 15 ("Use constexpr
whenever possible"):
Things to Remember
constexpr
objects areconst
and are initialized with values known during compilation.- [...]
constexpr
objects and functions may be used in a wider range of contexts than non-constexpr
objects and functions.
Macros work by substituting text. With macro the following example code will be ill-formed:
struct foo
{
int array_width{};
};
So in modern C++ one should prefer to avoid macros when there are alternatives available. Also it is a good idea to use UNIQUE_PREFIX_UPPER_CASE
naming convention for macros to avoid possible clashes with normal code.