Functions
The best way to develop and maintain a large program is to construct it from smaller pieces each of which are easier to manage (a technique sometimes referred to as Divide and Conquer). Functions allow the programmer to modularize the program.
Functions allow complicated programs to be parceled up into small blocks, each of which is easier to write, read, and maintain. We have already encountered the function main and made use of printf from the standard library. We can of course make our own functions and header files. A function has the following layout:
return-type function-name ( argument list if necessary )
{
local-declarations;
statements ;
return return-value;
}
If return-type is omitted, C defaults to int. The return-value must be of the declared type. All variables declared within functions are called local variables, in that they are known only in the function to which they have been defined.
Some functions have a parameter list that provides a communication method between the function, and the module that called the function. The parameters are also local variables, in that they are not available outside of the function. The programs covered so far all have main, which is a function.
A function may simply perform a task without returning any value, in which case it has the following layout:
void function-name ( argument list if necessary )
{
local-declarations ;
statements;
}
Arguments are always passed by value in C function calls. This means that local copies of the values of the arguments are passed to the routines. Any change made to the arguments internally in the function is made only to the local copies of the arguments.
In order to change or define an argument in the argument list, this argument must be passed as an address. You use regular variables if the function does not change the values of those arguments. You MUST use pointers if the function changes the values of those arguments.
Let us learn with examples:
#include <stdio.h>
void exchange ( int *a, int *b )
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf(" From function exchange: ");
printf("a = %d, b = %d\n", *a, *b);
}
void main()
{
int a, b;
a = 5;
b = 7;
printf("From main: a = %d, b = %d\n", a, b);
exchange(&a, &b);
printf("Back in main: ");
printf("a = %d, b = %d\n", a, b);
}
And the output of this program will be displayed as follows:
From main: a = 5, b = 7
From function exchange: a = 7, b = 5
Back in main: a = 7, b = 5 |
|