Consteval Specifier In C++

In this article, we will discuss the Consteval specifier in C++ with its syntax and examples.

What is the Consteval Specifier?

The consteval specifier is used to declare an immediate function in C++. The function that must be evaluated at compile time to obtain a constant is known as an immediate function. By ensuring that the function is only called at compile time, this specifier frees up the runtime overhead and allows the compiler to parse the function and use the result directly in the code.

In C++20, the new specifier consteval results in a function that can be evaluated at compile time. It guarantees that the function is called only in regular expressions, where the function and all its parameters are constants defined at compile time. By calculating values in terms of build time rather than run time, consteval allows for outrageous efficiency and efficiency.

Syntax:

It has the following syntax:

Example

consteval return_type function_name(parameter_list) { 
    // function body 
}

Example 1:

Let us take an example to illustrate the Consteval function in C++.

Example

#include <iostream>a
// A consteval function to calculate the square of a number
consteval int square(int n) {
    return n * n;
}
int main() {
    constexpr int result = square(5); // Evaluated at compile time
    std::cout << "Square of 5 is: " << result << std::endl;
    return 0;
}

Output:

Example 2:

Example

#include <iostream>
// A consteval function to calculate the factorial of a number
consteval int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);
}
int main() {
    constexpr int fact5 = factorial(5); // Evaluated at compile time
    std::cout << "Factorial of 5 is: " << fact5 << std::endl;
    return 0;
}

Output:

Example 3: Use Case - Compile-Time String Length Calculation

Example

#include <iostream>
// A consteval function to check if a number is even
consteval bool isEven(int n) {
    return n % 2 == 0;
}
int main() {
    constexpr bool result = isEven(10); // Evaluated at compile time
    std::cout << "10 is even: " << std::boolalpha << result << std::endl;
    return 0;
}

Output:

Key points:

Several key points of the consteval specifier are as follows:

  • In C++, a function can be specified to be evaluated at compile time by using the consteval specifier.
  • For verification at build time, the function defined by consteval has to have all of its arguments available.
  • Constructal tasks cannot contain runtime-only elements like dynamic memory allocation and I/O activities.
  • Routine input and programming logic are examples of scenarios where programming functions are employed when cumulative analysis time is necessary.

Input Required

This code uses input(). Please provide values below: