Skip to content
Related Articles

Related Articles

Improve Article

Assigning function to a variable in C++

  • Last Updated : 28 Jun, 2021
Geek Week

In C++, assigning a function to a variable and using that variable for calling the function as many times as the user wants, increases the code reusability. Below is the syntax for the same:

Syntax:

C++




// Syntax:
  
// Below function is assigned to
// the variable fun
auto fun = [&]() {
    cout << "inside function"
         << " variable";
};

Program 1: Below is the C++ program to implement a function assigned to a variable:

C++




// C++ program to implement function
// assigned to a variable
  
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    // Below function i.e., is
    // assigned to the variable fun
    auto fun
        = [&]() {
              cout << "Inside Function Variable";
          };
  
    // Call the function using variable
    fun();
  
    return 0;
}
Output



Inside Function Variable

Program 2: Below is the C++ program to implement a parameterized function assigned to a variable:

C++




// C++ program to implement parameterized
// function assigned to a variable
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    // Passing i and j as 2 parameters
    auto fun = [&](int i, int j) {
        cout << "Parameterised Function";
    };
  
    // Call the function using variable
    fun(4, 5);
  
    return 0;
}
Output
Parameterised Function

Program 3: Below is the C++ program to implement a function assigned to a variable that returns a value:

C++




// C++ program to implement the function
// assigned to a variable returning
// some values
#include <iostream>
using namespace std;
  
// Driver Code
int main()
{
    // Function taking 2 parameters
    // and returning sum
    auto sum = [&](int a, int b) {
        return a + b;
    };
  
    // Call the function using variables
    cout << "The sum is: "
         << sum(4, 5);
  
    return 0;
}
Output
The sum is: 9
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :