Function Execution and Variable Initialization
Explore the difference between the 'const', 'constexpr', 'consteval' and 'constinit' keywords.
We'll cover the following...
We'll cover the following...
Now it’s time to write about the differences between const
, constexpr
, consteval
, and constinit
. First, I discuss function execution and then variable initialization.
Function execution
The following program has three versions of a square
function.
Press + to interact
C++
#include <iostream>int sqrRunTime(int n) {return n * n;}consteval int sqrCompileTime(int n) {return n * n;}constexpr int sqrRunOrCompileTime(int n) {return n * n;}int main() {// constexpr int prod1 = sqrRunTime(100); ERRORconstexpr int prod2 = sqrCompileTime(100);constexpr int prod3 = sqrRunOrCompileTime(100);int x = 100;int prod4 = sqrRunTime(x);// int prod5 = sqrCompileTime(x); ERRORint prod6 = sqrRunOrCompileTime(x);}
As the name suggests: the ordinary function sqrRunTime
(line 3) runs at run time, the consteval
function ...