When we begin programming in C/C++, we generally write one main() function and write all our logic inside this. This approach is fine for very small programs, but as the program size grows, this become unmanageable. So we use functions. We write code in the form of functions. The main function always acts as a driver function and calls other functions.
#include <iostream>
using namespace std;
int add( int num1, int num2)
{
return (num1 + num2);
}
int main()
{
int num1 = 12, num2 = 34;
cout << add(num1, num2);
return 0;
}
|
We can also write function call as a parameter to function. In the below code, first add(num1, num2) is evaluated, let the result of this be r1. The add(r1, num3) is evaluated. Let the result of this be r2. Finally add(r2, num4) is evaluated and its result is printed.
#include <iostream>
using namespace std;
int add( int num1, int num2)
{
return (num1 + num2);
}
int main()
{
int num1 = 12, num2 = 34, num3 = 67, num4 = 12;
cout << add(add(add(num1, num2), num3), num4);
return 0;
}
|
Another example of function calling function are as follows : –
#include <iostream>
using namespace std;
int add( int num1, int num2);
int sub( int num1, int num2);
int mul( int num1, int num2);
int calculator( int num1, int num2, int option)
{
if (option == 1) {
return add(num1, num2);
}
if (option == 2) {
return sub(num1, num2);
}
if (option == 3) {
return mul(num1, num2);
}
}
int add( int num1, int num2)
{
return (num1 + num2);
}
int sub( int num1, int num2)
{
return (num1 - num2);
}
int mul( int num1, int num2)
{
return (num1 * num2);
}
int main()
{
int num1 = 10, num2 = 5;
int option;
option = 1;
cout << calculator(num1, num2, option);
return 0;
}
|