Understanding Functions in C++ |
To re-use the same part of a program, we can define a function, which takes parameters, and returns a result of various type. Typical definition contains theType of the value it returns, an identifier for its name, and the list of parameters with their types. The evaluation of a function is done when the call operator () is used. One argument (i.e. an expression) is provided to each parameter.
An example makes things clearer.
#include <iostream>
// This function has one parameter called x
double square(double x) { return x*x; }
// This one has two parameters called x and y
// It returns the largest k so that y^k <= x
int maxexpon(double x, double y) {
double z = 1;
int result = 0;
while(z <= x) { result++; z = z * y; }
return result-1;
}
int main(int argc, char **argv) {
double a, b;
cin >> a >> b;
// The argument is a for the first call and a+b for the second
cout << square(a) + square(a + b) << ’\n’;
// The two arguments are and b
cout << maxexpon(a, b) << ’\n’;
}
Note that as for loops, the scope of the parameters and variables defined in the
function definition is the function statement itself.