Functions are a group of statements that are executed when that function is called. When the function call is encountered by
main( ),
main( ) stops in its place and executes the function that was called. For example:
1 2 3 4 5 6 7 8 9 10 11 12
|
void Function( void )
{
// Once main( ) stops, the following statements are executed.
std::cout << "Inside Function( )" << std::endl;
}
int main( )
{
Function( ); // main( ) will stop here.
// When Function( ) returns, main( ) will resume from here.
}
|
Once
main( ) reaches the call to
Function( ),
main( ) will stop its execution until it either executes all the statements within the body of the called function (usually the case when the return type-specifier is
void), or, when a
return statement is encountered of the called function. Once the function is finished,
main( ) will resume from the point where is stopped.
Functions consist of 4 parts:
Return Type-Specifier:
This indicates the type of data that the function will return after its execution. A return type-specifier of
void indicates that the function doesn't return anything. If a function has a return type-specifier other than
void, it must return a piece of data. However, a function cannot return more than one piece of data. This includes arrays.
Identifier:
This gives the function a name. The identifier lets the compiler/linker know which function you wish to call.
Parameter List:
This is a group of objects called
Parameters. Each parameter is declared the same way as a normal variable. For example:
1 2 3 4
|
void Function( int ParameterOne )
{
//...
}
|
Here,
ParameterOne is a parameter. The data given to it during the function call, is called an
Argument. Parameters can be pointers, references, references to pointers, etc.
Body:
The body is where the statements reside. It is also where the
return statement lives. The body is the place where
main( ) jumps to when you call the function within
main( ).
Functions can be declared as prototypes. Prototype functions are functions without the body. However, you must define the function body later on, preferably after
main( ). For example:
1 2 3 4 5 6 7 8 9 10 11 12
|
void Function( int ); // This is a function prototype.
int main( )
{
Function( 10 );
return 0;
}
void Function( int Param )
{
// ...
}
|
I hope this helps you :)
Wazzak