1

in case that we can write a int variable in c++ with const and constexpr modifiers which one is more preferred and why?

const int x {5}; constexpr int x {5}; 

aren't these two lines the same?

6
  • 1
    This question satisfy you? stackoverflow.com/questions/4748083/… Commented Apr 10, 2024 at 9:00
  • 2
    1. Complex evaluation at compile time. 2. UB leads to compilation errors. Demonstrated example no difference. Commented Apr 10, 2024 at 9:02
  • why the second leads to an error, are you sure? Commented Apr 10, 2024 at 9:05
  • 2
    1 and 2 are the reasons to use constexpr, not referring to the lines in your question. Commented Apr 10, 2024 at 9:08
  • const vs constexpr on variables Commented Apr 10, 2024 at 9:12

1 Answer 1

1

Use constexpr whenever you can, e.g. in your case.

constexpr means that the value is constant, known at compile time and allows some computations and optimizations during the compile time.

More info: https://en.cppreference.com/w/cpp/language/constexpr

const means that value is set at declaration and will not change from that moment, however this occurs at program runtime.

More exactly:

Such object cannot be modified: attempt to do so directly is a compile-time error, and attempt to do so indirectly (e.g., by modifying the const object through a reference or pointer to non-const type) results in undefined behavior.

From: https://en.cppreference.com/w/cpp/language/cv

Some example to play with:

#include <iostream> int main() { // can be both const and constexpr, constexpr is stronger constexpr int a = 5; int temp; std::cout << "Give me number:" << std::endl; std::cin >> temp; // can not be constexpr const int b = temp; std::cout << "Numbers " << a << " " << b << std::endl; return 0; } 
Sign up to request clarification or add additional context in comments.

5 Comments

in OPs code both x are known at compile time
You are right, adding something along lines "use constexpr if you can". Thanks!
"const means [...] this occurs at program runtime." is not correct, again, see OPs example.
Well in OPs example, I would say the compiler would understand it is constexpr, but it is not guaranteed in general, see the example in my answer. const means approximately the thing you used [...] for. Link to precise definition is added.
@RomanPavelka It happens to be guaranteed for const integral (and enumeration) types which are initialized by constant expressions. That's a historical exception. These cases are effectively constexpr even if not declared so. But you are correct that the meaning is different for all other types or if the initialization is not a constant expression (as in your example).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.