Philipp Claßen
Philipp Claßen

Reputation: 43969

Should I always replace 'const int' with 'constexpr int' in C++11 whenever possible?

Would you replace

const int one = 1;
const int two = 2;

with this?

constexpr int one = 1;
constexpr int two = 2;

Is my understanding correct that both blocks are semantically identical and that it is currently merely a matter of taste?

On the other hand, as constexpr implies const, you could argue that it is more consistent to always prefer the more restrictive form, even in trivial situations where it does not make a difference?

(I understand that the situation completely changes when the expression on the right side are allowed to be more complicated. So for clarification, the question only focuses on the most simple case where the expression is a fixed integer number.)

Upvotes: 14

Views: 2093

Answers (2)

Zhang
Zhang

Reputation: 3346

You don't have to replace const with constexpr in such case,

const int one = 1;
const int two = 2;

If you have a constant variable like this,

const int three = one + two;

you would better to define it as constexpr

constexpr int three = one + two;

to make sure three will be computed during the compilation period.

I know someone would argue, the modern compiler will do the optimizing, to even compute it just with const.

I just take an example for the usage of constexpr, the calculation maybe complicated and the compiler couldn't optimize it.

Upvotes: 0

Andy Prowl
Andy Prowl

Reputation: 126432

I think your statement saying that const and constexpr "are semantically identical" should be revised: they both declare objects whose value cannot change, but constexpr also requires the initializer expression to be computable at compile-time.

Now if the expression on the right-hand side cannot be computed at compile-time, using constexpr is out of the question. On the other hand, as long as the initializer is a literal, you could use constexpr, but keep into account what the semantics of your variable is: does your constant variable really represent something whose value should be computable at compile-time?

In a SW maintenance/evolution optics, it is possible that you will change the way you initialize your variable throughout time: today the initializer is a literal, tomorrow it might be a more complex expression.

Regardless of the way you are assigning it a value now, do you think that i will ever need to be initialized by anything else than a literal, and that the initializing expression may not be computable at compile-time? If that is the case, then just make your variable const, even though you are currently initializing it with a literal; otherwise, make it constexpr.

In other words, choose the qualifier that best expresses the semantics of your variable.

Upvotes: 13

Related Questions