Open In App

Immediate Functions in C++

In this article, we will discuss the immediate function used in C++.

Immediate Function:



Below given some important terms related to Immediate Function:

constexpr function

Below is the C++ program illustrating the use of constexpr function:






// C++ program demonstrates the use of
// constexpr
#include <iostream>
using namespace std;
  
// Constexpr function if replaced with
// consteval, program works fine
constexpr int fib(int n)
{
    // Base Case
    if (n <= 1)
        return n;
  
    // Find the Fibonacci Number
    return fib(n - 1) + fib(n - 2);
}
  
// Driver Code
int main()
{
    // Constant expression evaluated
    // at compile time
    const int val = fib(22);
  
    cout << "The fibonacci number "
         << "is: " << val << "\n";
  
    return 0;
}

Output
The fibonacci number is: 17711

Explanation:

consteval function:

Below is the C++ program illustrating the use of consteval function:




// C++ program illustrating the use
// of the consteval function
  
#include <iostream>
using namespace std;
  
// If constexpr replaces with consteval
// program gives an error in C++20
constexpr int fib(int n)
{
    // Base Case
    if (n <= 1)
        return n;
  
    return fib(n - 1) + fib(n - 2);
}
  
// Driver Code
int main()
{
    // This expression is not evaluated
    // at compile time
    const int val = fib(rand() % 20);
  
    cout << "The fibonacci number is: "
         << val << "\n";
  
    return 0;
}

Output
The fibonacci number is: 2

Explanation:

Conclusion:


Article Tags :