2

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.

Mark
  • 325
  • 1
  • 16

2 Answers2

2

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 consts, enums, and inlines to #defines"):

Things to Remember

  • For simple constants, prefer const objects or enums to #defines
  • [...]

From S. Meyers, Effective Modern C++, Item 15 ("Use constexpr whenever possible"):

Things to Remember

  • constexpr objects are const 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.
lubgr
  • 37,368
  • 3
  • 66
  • 117
1

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.

user7860670
  • 35,849
  • 4
  • 58
  • 84