What is consteval in C++?

We use the consteval specifier in C++ to declare an immediate function. An immediate function is a function that must be evaluated at the compile-time to produce a constant. In other words, an immediate function is executed at compile-time.

Consteval vs Constexpr

The constexpr specifier is the same as the consteval specfier, except for the fact that if a function declared with consteval does not return a compile-time constant, the function returns an error.

Declaration

We can declare an immediate function with the consteval specifier as shown below:

consteval returnType funcName (parameters)
{
//function body
}
  • returnType: The return type of the immediate function.
  • funcName: The function identifier of the immediate function.
  • parameters: The input parameters of the immediate function.

Code

Consider the code snippet below, which demonstrates the use of the consteval specifier:

#include <iostream>
consteval int add(int a, int b) {
return a + b;
}
int main() {
std::cout << "sum(2 + 5)= " << add(2, 5) << std::endl;
const int a = 2;
const int b = 5;
std::cout << "sum(2 + 5)= " << add(a, b) << std::endl;
int a2 = 2;
int b2 = 5;
//std::cout << "sum(2 + 5)= " << add(a2, b2) << std::endl; //Error: Call does not produce a constant
return 0;
}

Output

sum(2 + 5)= 7
sum(2 + 5)= 7

Explanation

An immediate function add is declared in line 3 using the consteval specifier.

  • line 9: Two constants 2 and 5 are passed to the immediate function add. It is a valid invocation, so the function returns the answer.
  • line 13: Two constants, integers a and b, are passed to the immediate function add. It is a valid invocation, so the function returns the answer.
  • line 17: a2 and b2 are not constant expressions. Thus, the invocation of the immediate function is not valid and the function returns an error.
Copyright ©2024 Educative, Inc. All rights reserved