Assigning function to a variable in C++
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 << "Parameterized Function" ; }; // Call the function using variable fun(4, 5); return 0; } |
Output:
Parameterized 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
Please Login to comment...