What is the difference between const int x and constexpr int x ? Which of these should be used?
- Check out this answer - stackoverflow.com/questions/14116003/… - user227465
- In what context? - αλεχολυτ 4:05
- @alexolut in general - user227581
- 2wrote an article about this - you can read. - ixSci 4:38
- @ixSci thanks! - user227581
2 answers
The simplest example. This program is compiled
#include <iostream> struct A { constexpr static double x = 10.0; }; int main() { A a; return 0; } And this program is not.
#include <iostream> struct A { const static double x = 10.0; }; int main() { A a; return 0; } Essential meaning also occurs when this specifier, constexpr , is used for functions.
As you know, only member functions of a class can have a const qualifier that is related to the object for which the given member function is called.
Normal functions cannot be constant.
The constexpr introduced to force the compiler to create objects at the stage of the compilation and to use them as compile-time constants.
For example, it is known that the C ++ standard requires a constant expression to specify the dimension of an array. Using the constexpr you can specify the size of an array using some functions. For example,
#include <iostream> struct A { constexpr A( bool b ) : n( b ? 5 : 10 ) {} size_t n; }; int main() { int a[A( true ).n]; int b[A( false ).n]; int i = 0; for ( int &x : a ) x = i++; i = 0; for ( int &x : b ) x = i++; for ( int x : a ) std::cout << x << ' '; std::cout << std::endl; for ( int x : b ) std::cout << x << ' '; std::cout << std::endl; return 0; } Output of the program to the console
0 1 2 3 4 0 1 2 3 4 5 6 7 8 9 Using constexpr allows constexpr to do metaprogramming at compile time, as an alternative opportunity for template metaprogramming.
const int x - the variable x should not change while the program is running, and constexpr int x - it should also get its value at compile time ...
For example,
int n; cin >> n; const int x = n*n; It will work, x will get its value, which cannot be changed - but it will receive while the program is running.
If you write constexpr - it will not compile, because at compile time x not known.
Accordingly, use what is suitable for your purposes. Where possible - better constexpr , where not - just const .