i'm confused with 2 keywords

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?
i'm so sorry.. maybe because i'm Portuguese. but can you be a little more simple? please
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.
if constexpr is more for optimization and time, why learned on constants chapter(on some books)?
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 {
 static constexpr int result = N * Factorial<N-1>::result;
};
 
template <> struct Factorial<0> {
 static constexpr int 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
  const int z {x*y}; // OK
  // ++z; // ERROR: increment of read-only variable 'z'
  std::cout << z << '\n';
  return 0;
}
Last edited on
i think we get 20 on cout.
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.
thanks for all to all
Topic archived. No new replies allowed.