DEV Community

Discussion on: Magic numbers and how to deal with them in C++

Collapse
 
loki profile image
Loki Le DEV

Does constexpr replace const for these kind of constants?

Can we just do this:

// Foo.cc

// Modern C++ style
constexpr auto MY_CONSTANT{42};

every time we need a constant and it will behave the same as const with added benefits of constexpr ?

Collapse
 
10xlearner profile image
10x learner

Yes, it can.

And I encourage you to do so, since you can end up with methods and functions using only elements with constexpr elements and add the constexpr keyword to those functions/methods and allow them to be performed by the compiler, at compile time, instead of being executed at run time.

Here is a godbolt link if you want to experiment with constexpr and C++ in general ;)

I will also add a link to the documentation of constexpr in the article so that people can easily find it

Collapse
 
10xlearner profile image
10x learner

I remembered those 2 conference videos about constexpr. You may found it useful to see the benefits of constexpr ;)

constexpr ALL the Things!”
Rich Code for Tiny Computers: A Simple Commodore 64 Game in C++17