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?
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; } x are known at compile timeconst means [...] this occurs at program runtime." is not correct, again, see OPs example.const means approximately the thing you used [...] for. Link to precise definition is added.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).
constexpr, not referring to the lines in your question.