Function Definition
After you have written the prototype you are ready to write the definition of the function! The definition of a function consists of the function header and its body. The header is exactly like the function prototype, except that the parameters must be named, and there is no terminating semicolon. The body of the function is a set of statements enclosed in braces. Function arguments do not have to all be of the same type. It is perfectly reasonable to write a function that takes an integer, two longs, and a character as its arguments.
Any valid C++ expression can be a function argument, including constants, mathematical and logical expressions, and other functions that return a value. Even though you can write a function that is 3 pages long, I would not recommend it! It is best to make several small functions, that are easy to understand, and in the long run, much easier to debug.
Here is an example of the definition of the function listed above:
 | |  | | |
int addTwoNumbers( int n1, int n2 )
{
return (n1 + n2);
} |
|  |
|
As you can see the parameters of this function are the same as the prototype, as they should be; but the n1 and the n2 don’t have to be the same as the prototype, you could write:
 | |  | | |
int addTwoNumbers( int number1, int number2 )
{
return (number1 + number2);
} |
|  |
|
this would give you the same results. But if you were to rewrite the function definition so that you would have a return value of a double instead of an int and kept the same function prototype you would get an error.
For example:
 | |  | | |
//prototype, return type int
int addTwoNumbers ( int n1, int n2 );
//Function Definition
double addTwoNumbers( int number1, int number2 ) //error, return type double not int
{
return (number1 + number2);
} |
|  |
|
As a final reminder, just to ensure that you understand the difference between a function prototype and a function definition here is the syntax:
 | |  | | |
//Function Prototype Syntax
return_type function_name ( [type [parameterName]]...);
//Function Definition Syntax
return_type function_name ( [type parameterName]...)
{
statements;
} |
|  |
|
Now that you have mastered that, we can move onto some more interesting aspects of the function.
Please Rate this Code: