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++
auto fun = [&]() {
cout << "inside function"
<< " variable" ;
};
|
Program 1: Below is the C++ program to implement a function assigned to a variable:
C++
#include <iostream>
using namespace std;
int main()
{
auto fun
= [&]() {
cout << "Inside Function 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++
#include <iostream>
using namespace std;
int main()
{
auto fun = [&]( int i, int j) {
cout << "Parameterized Function" ;
};
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++
#include <iostream>
using namespace std;
int main()
{
auto sum = [&]( int a, int b) {
return a + b;
};
cout << "The sum is: "
<< sum(4, 5);
return 0;
}
|
Last Updated :
19 Apr, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...