Function Declaration, Definition and Calling

 

Function Declaration:

Before a function can be implemented or used, it must be declared*. A function’s declaration is its prototype. Function prototypes usually appear at the beginning of a module, ahead of any reference to the function.

 

Example:

void getred(char, int, int);

Note that the prototype defines the function identifier, getred,

Its return type, void, and the number and type of its calling parameters, which in this case is a char and two int’s. Identifiers for the individual parameters are optional and need not be the same identifiers that will be used in the definition of the function.

 

If a function is to take a variable number of parameters, then an ellipsis (…) is used to signify that the parameters to follow are indefinite.

 

*Strictly speaking, a prototype is not required unless the function is to be used before it is defined. What that means is that if the definition of the function stands physically in a part of the program that is ahead of where it is first referenced, then the definition of the function serves as its prototype.

 

 

Function Definition:

A function’s definition is the code for its function header and statement body. The function header must match the function prototype, except that parameter names may differ.

 

 

Calling Functions:

A program calls a function by specifying the function’s name with arguments in parenthesis. The arguments match the types of the function’s parameter list.

 

If the function returns a value, the function call may be used in an expression, such as on the right side of an assignment or initialization as shown here:

Int foo = getfoo(123);

 

Conversely, if a function declares a return type of void, then it may NOT return a value and the call to the function CANNOT appear in an expression or on the right side of the assignment statement.