Monday, October 19, 2015

On functions


Functions in C

Up to this point, we have described how to use functions, but not how to code them.  It turns out that in C, it’s relatively straightforward to code your own function.  Every function begins with a statement that looks very much like a function prototype.  However, while a function prototype tells the compiler what arguments the function takes and what type of value it returns, the function definition is always followed by the body of the function – the series of variable definitions and statements that do the work of the function.

The following C code implements the function average_ints(), which averages three values of type int and returns their average as a double.

/*Function to average 3 integers */

double average_ints(int i, int j, int k)
 {
double average;
average = (i+j+k)/3.0;
return (average);
}

A few key ideas are illustrated in this example.  Note that the first line of the function defines the type of the value the function returns, in this case, a double.  Like a function prototype, it also defines the types of the arguments.  However, in this case the arguments are given variable names.  These names can then be used in the body of the function.  If you think about what happens when the function average_ints() is invoked, the copies of the arguments can be thought of as being assigned to the variables i, j, and k.   The variables used in this function like i, j, k and average are internal variables.  They are internal variables since they are valid only within the function and are not global.

One of the key features of functions is the use of the return statement.  The return statement allows you to pass the result of a function back to the calling function:  In this case, the main() function. 

/*Another version of average_ints() */

double average_ints(int i, int j, int k)
{
             return ( (i+j+k)/3.0 );
}

So, any C function can be invoked or called by another.  The invoking function may pass information tot he invoked function and the invoked function may return information to its invoker.


A function’s header consists of:
·      Data type returned, or the keyword void if the function does not return a value
·      Function’s name
·      In parentheses, a list of parameters and their types separated by commas, or the key word void if the function has no parameters

Specifying the data type is optional:  If omitted, it defaults to int.  However, it is good practice to always specify the data type.

The special key word void is used to indicate that a function doesn’t return a value or that it doesn’t have any arguments.  For example, the function prototype

            void no_result(double);

declares that no_result() does not return a value.  Similarly, the function prototype

            int no_arguments(void);

indicates that the function returns an integer value but does not have any arguments.

No comments:

Post a Comment