What is the difference of declaring a variable as constexpr const and constexpr?

Asked

Viewed 133 times

1

What is the difference of declaring a constant as constexpr const for only one constexpr?

constexpr const float max_height = 3.0f;

constexpr float max_height = 3.0f;

1 answer

1


constexpr informs the compiler that it has the result of that expression at compile time so it can optimize and solve without taking that to execution. const only ensures that that value will not be changed throughout the execution.

In practice in the two cases shown it gives in the same because in fact it is a literal, it would make a difference in an expression, a function, something that depends on some information that is not directly present there in the statement. And surely something solved in the compilation cannot be changed. It could even do:

const float max_height = 3.0f;

I put in the Github for future reference.

  • But in C++11 onwards it is not recommended to prefer the use of constexpr instead of const?

  • Why would you use something that doesn’t give you a new edge on what you want? consterpr has another semantics, as I answered.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.