Function Parameters
A function can be provided input in the form of zero or more variables called
parameters. Parameters are created when the function is called, and they are
assigned the values provided as arguments. An example of a function with one
parameter is:
int parFunction(char parameter1)
{
return parameter1;
}
parFunction() returns an
int value and takes a
char as a parameter. The only statement
contained within the function's implementation block returns the input
parameter, which is interpreted as an
int.
When the function is called within another function, for example within
main(), an argument has to be passed to it,
which will be assigned to
parameter1.
parameter1 is created when the function is
entered and destroyed when the function is exited. For example, the call:
parFunction('t');
will call the function, assigning
't' to
parameter1 and finally returning
't''s ASCII code.
Functions can return any type but arrays. Further, functions can contain local
variables: i.e. variables declared within the function's body that are unknown
outside the function and are deleted (go out of scope) once the function is
exited (just like parameters).
anotherFunction()
contains a local variable:
void anotherFunction() // prints alphabet
{
char localVariable = 'a';
while(localVariable <='z')
{
cout << localVariable << " ";
localVariable++;
}
}
The function above contains one local variable, created within the function
and destroyed when the function returns.
Also, the function does not return any value. For such a reason its return type
is
void.
Example
#include <iostream>
using namespace std;
int parFunction(char parameter1)
{
return parameter1;
}
void anotherFunction() // prints alphabet
{
char localVariable = 'a';
while(localVariable <='z')
{
cout << localVariable << " ";
localVariable++;
}
}
int main()
{
cout << parFunction('e') << endl;
anotherFunction();
}
Output
101
a b c d e f g h i j k l m n o p q r s t u v w x y z