Functions in C++ are similar to methods in Java. But there is an important difference: Java allows you to define methods in any order, but a C++ program can only use a function after the function has been defined. (See below for an exception.) Order your function definitions accordingly. You can write
int sqr(int x)
{
return x*x;
}
int fourthPower(int x)
{
return sqr(sqr(x));
}
but not
int fourthPower(int x)
{
return sqr(sqr(x));
}
int sqr(int x)
{
return x*x;
}
A function prototype is a function heading followed by a semicolon. For example, suppose that function parent is defined as follows.
int parent(const int n)
{
return (n+1)/2;
}
A prototype for parent is:
int parent(const int n);A prototype is a promise that a function will be defined somewhere in the program, and you can use a function anywhere after a prototype for it, even if it is defined after it is used. So
int sqr(int x);
int fourthPower(int x)
{
return sqr(sqr(x));
}
int sqr(int x)
{
return x*x;
}
is allowed.