FUNCTIONS

 

Every C function consists of two parts, a function header and a function body

<function header>

{

            <optional variable declarations>

            <executable statements>

}

A function header consists of the function’s name, the number and kind of arguments it expects when you call it, and the type of value, if any, it returns when its job is done.

 

The function header:

<return type><function name>(<list of formal parameters>)

 

Example:  int calcPrice(int x, double cost)

 

The number of formal parameters must be the same as the number of arguments (called actual parameters) when the function is called.

 

For example, for the function call:

            rectArea = area(width, length); ß the value calculated in area would be assigned to the variable rectArea.

 

The function header might be:

            int area(int w, int l) ß the names of the variables do NOT need to be the same in the calling function and the called function.

 

The function body is made up of executable statements.  It is a complete, brief program that produces some effect.  It operates on the passed data and return, at most, one value.  It is enclosed in {}.

 

The function body for area might look like this:

            int area(int w, int l)

            {

                        return(w*l); ß you usually have more statements than this

            }

A function prototype is a declaration of the function to the rest of the C program.  It must be placed in the program before the function is called – usually before the main function.

<return type> <function name>(<list of data types of the passed parameters>); ß note the semicolon

For the area function, the prototype would look like this:

            int area (int, int);

 

A function may return nothing or be passed nothing – in that cause you would use void:

 

            void example(void); ß you may also leave the return type empty

 

Return to 1336 home page