Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `constexpr` and `#define`

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.

like image 910
Antonin GAVREL Avatar asked Sep 13 '25 17:09

Antonin GAVREL


1 Answers

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.

like image 63
SimonFarron Avatar answered Sep 15 '25 08:09

SimonFarron