Difference between `constexpr` and `#define`

Viewed 7320

So I read the interesting answers about what are the differences between constexpr and const but I was curious about are the differences between #define and constexpr ? I feel like constexpr is just a #define where the type can be chosen.

2 Answers

Statements defined using #define are called macros. And macros are used in a multitude of uses.

  1. We can use them to conditionally compile sections of code.
#ifdef ONE
int AddOne(int x) { return x + 1; }

#else
int AddTwo(int x) { return x + 2; }

#endif
  1. When we don't need to store constants in a variable.
#define MAX_BOUND 1000
#define MIN_BOUND 10
  1. For places where we can use a macros to change the type of data.
#ifdef USE_WIDE_CHAR
#define TEXT(...)    L##__VA_ARGS__

#else
#define TEXT(...)    __VA_ARGS__

#endif
  1. To define keywords based on a condition.
#ifdef BUILD_DLL
#define DLL_API __declspec(dllexport)

#else
#define DLL_API __declspec(dllimport)

#endif

Since they are resolved before the actual compilation phase, we can make small improvement to the source code depending on certain factors (platforms, build systems, architecture, etc...).

constexpr essentially states that a variable or function can be resolved at compile time, but is not guaranteed.

I feel like constexpr is just a #define where the type can be chosen.

Its not completely true. As I stated before, because they are resolved before the compilation phase, we can take some advantages of it. The only common use would be for constant values which the compiler could easily replace as an optimization. Apart from that, the use cases are different.

You are quite correct.

#define (also called a 'macro') is simply a text substitution that happens during preprocessor phase, before the actual compiler. And it is obviously not typed.

constexpr on the other hand, happens during actual parsing. And it is indeed typed. Comes without saying that, wherever you can, using constexpr is a bit safer.

Related