i'm review the C++(reading the book).
theres, for now, 2 things that i really didn't understand:
1 - what really means constexpr?
2 - what really means inline?
i continue confused what mean and what for :(
can anyone explain to me?
constexpr: able to be evaluated at compile time const: promise not to change the value inline: instead of "calling" the function by jumping to its address, just copy the code of the function "in-line" at the point of the call.
constexpr was introduced in C++11. Some/most books are older.
constexpr is const, but it is more.
What calculations does this program do when it runs?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
template <int N> struct Factorial {
staticconstexprint result = N * Factorial<N-1>::result;
};
template <> struct Factorial<0> {
staticconstexprint result = 1;
};
int main() {
std::cout << Factorial<5>::result << '\n';
return 0;
}
An object can be const, but have different value every time we run the program:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
int main() {
int x;
int y;
std::cin >> x >> y;
// constexpr int z {x*y}; // ERROR: cannot compute during compilation
constint z {x*y}; // OK
// ++z; // ERROR: increment of read-only variable 'z'
std::cout << z << '\n';
return 0;
}
The program prints out "120", but it makes no calculations when it runs. The binary effectively has instructions for std::cout << "120\n";
in it. Just a constant value. No function calls. No multiplication.