consteval specifier in C++

Hello folks! Today, we will discuss consteval specifier in C++. Consteval specifier declares an immediate function to produce constant. This means that every potentially evaluated call should produce a compile-time constant expression directly or indirectly. The compiler evaluated the function at compile time.If while declaring a function or function template we use a consteval specifier, then all their declarations must contain that specifier. The consteval specifiers should be inline.

An immediate invocation is when the evaluated invocation of an immediate function produces a constant expression. Hence, consteval specifiers have immediate invocation.

We shouldn’t apply consteval specifiers to destructors, allocation functions, or deallocation functions. We can apply one of the constexpr, consteval and constinit specifiers only within the same sequence of declaration specifiers.

The following C++ code snippet can explain the use of consteval more appropriately :

consteval int sum(int a,int b) {
  return a+b;
}
constexpr int r = sum(3,4); 
cout<<r;
Output
7

If we give a new value to r, it will show an error.

Leave a Reply

Your email address will not be published. Required fields are marked *