Consider this program
#include <iostream>
double getRadius()
{
std::cout << "Enter the radius: ";
double radius{};
std::cin >> radius;
return radius;
}
void calculateArea(double r)
{
std::cout << "The area of the circle is "
<< 3.14159 * r * r;
}
int main()
{
double x = GetRadius();
CalculateArea(x);
}
The return value of GetRadius() is stored in a variable and passed into CalculateArea(). x only exists act as the interface between the two functions.
We can do better.
Doing Better
We merge these two instructions in one line.
calculateArea( getRadius() ); // A function is the argument into another function
The return value of getRadius() is used as the argument in calculateArea(). This is possible since the function returns a value.
In this program, getRadius() is intended to be used alongside CalculateArea(). Embedding it in one line makes this relationship explicit.
NOTE: We’re not passing in a function into another function. That is called a function pointer.
This allow us to condense our programs albeit at the expense of clarity. I like it since I’m a sucker for conciseness.
The function in the argument executes first, then the outer function:
Enter the radius: 12.5 // 1st function call
The area of the circle is 490.873 // 2nd function call