Declaration of functions
- Abstract:
It is quite easy to declare functions in C++. The basic
building blocks look as follows:
type function_name(type argument1, type argument2, ...) {
body;
return function_value;
}
|
It is mandatory that the function_value to be returned
is of the same type as the type of the function declaration.
- A first example:
Let me fill these bones with some "meat", i.e. an example:
double power(double value, int exponent) {
if (exponent == 0) return 1.;
double result = value;
if (exponent > 0) {
for (int i=1; i < exponent; i++)
result *= value;
return result;
}
for (int i=1; i < -exponent; i++)
result *= value
return 1./result;
}
|
There are a couple of features here that are worth highlighting:
- The function definition can be - in principle - arbitrary
complicated.
- You can have more than one return-statement in your
declaration.
- When you call this function, the two arguments need to be
of the same type as in the declaration and in the same
sequence.
By the way, in the example above, do you see a possible error ?
- void-functions:
There is the option to have functions with no values to be
returned. They will have an "empty" return-statement,
for instance more involved print-functions etc.. such functions
come with the type . As an example, consider
void print_power(double value, int exponent) {
if (exponent == 0) {
cout << 1. << endl;
return;
}
double result = value;
if (exponent > 0) {
for (int i=1; i < exponent; i++)
result *= value;
cout << result << endl;
return;
}
for (int i=1; i < -exponent; i++)
result *= value
cout << 1./result << endl;
}
|
- Default arguments:
You can give defualt arguments in your function declaration by
the follwoing construction:
type function_name(type argument1 = default_value1,
type argument2, ...) {
body;
return function_value;
}
|
Note, that you can take any argument and supply it with a default
value. The only problem here is a possible ambiguity, since
given arguments are matched from left to right. When the compiler
runs out of arguments in the call to the function it will start
using up the default values. Hence, in order to be consistent
with this scheme, it is mandatory tohat in the declaration
sequence the arguments with default values follow those without.
In our example above you would have for instance:
double power(double value = 1., int exponent = 0) {
if (exponent == 0) return 1.;
double result = value;
if (exponent > 0) {
for (int i=1; i < exponent; i++)
result *= value;
return result;
}
for (int i=1; i < -exponent; i++)
result *= value
return 1./result;
}
|
and you would be allowed to do the following calls:
power(2.,5);
power(7);
power(2.);
power();
|
Can you imagine what would be the results ?
They would be 32.,1.,1.,1. .
[prev]
[top]
[next]
|