A function is the fundamental building block of any program, as functions
perform the tasks required in that program. The most important in a C++
program is called main ( ). The main ( ) function is automatically executed
when the program is run. In effect, main ( ) is the program. A typical
main function looks like this:
Int main (void)
{
// Your code here
return 0;
}
-
The // characters mark the beginning of a comment all text following // on a line is ignored by the compiler.
-
The first line specifies the return type of the function, its name,
and what arguments, if any the function requires.
-
In the above example the function is called main, and will
return a value of type int (thus int main). This function requires
no arguments, or inputs to perform its task, so the type is specified
as void.
- The instructions to be executed are enclosed between the curly brackets.
-
The return keyword is used to exit the function and pass a return
value back to the functions caller. If return is omitted, a function
call will exit at the closing curly bracket with no value returned.
However, in this example, the compiler would not allow such as an
implied return
because the main function was defined as returning
an int value. Thus, in this function a value must explicitly
be returned.
Where a function does not need to return a value, it
may be defined as void, so for a function which uses two integer values,
but returns no result:
Void NoValueReturned(int x, int y)
{
// code here
}
Writing functions
Consider a function, which calculates the square of a number:
Int Square(int input)
{
return(input * input);
}
This function returns a value of type int,
is called Square and requires one input argument, of type int, called input
by that function. Inside the function, input refers to whatever int value
was passed to the function. As can be seen below, the calling code does
not have to call the int it passes to this function input :so long as the
callers value is of type int it can be used as an input to Square(). Similarly
to a variable, before this function can be used by other code, it must first
be declared:
void main (void)
{
int Square( int ); //declare Square ( )
int x, y, result; //declare variables
x = 4 * 2;
y = x / 7;
result = Square ( y ); //call square function with y as input
}