Constexpr functions in a runtime context

In the previous example, the summed values, (3, 4, 5), were known to the compiler at compile time, but how do constexpr functions handle variables whose values are not known until runtime? As mentioned in the previous section, constexpr is an indicator to the compiler that a function, under certain conditions, can be evaluated at compile time. If variables with values unknown till runtime are invoked, they will be evaluated just like regular functions.

In the following example, the values of x, y, and z are provided from the user at runtime, and therefore, it would be impossible for the compiler to calculate the sum at compile time:

int x, y, z; 
std::cin >> x >> y >> z; // Get user inputauto value ...

Get C++ High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.