The Function Body
The function body in a function is the place that contains variable declarations and C statements. The task of a function is accomplished by executing the statements inside the function body one at a time.
Listing 3.1 demonstrates a function that adds two integers specified by its argument and returns the result of the addition.
TYPE
Listing 3.1. A function that adds two integers.
/* This function adds two integers and returns the result */
int integer_add( int x, int y )
{
int result;
result = x + y;
return result;
}
ANALYSIS
As you learned in Chapter 02, line 1 of Listing 3.1 is a comment that tells the program-mer what the function can do.
In line 2, you see that the int data type is prefixed prior to the function name. Here int is used as the function type, which signifies that an integer should be returned by the function. The function name shown in line 2 is integer_add. The argument list contains two arguments, int x and int y, in line 2, where the int data type specifies that the two arguments are both integers.
Line 4 contains the opening brace ({) that mar ks the start of the function.
The function body is in lines 4_6 in Listing 3.1. Line 4 gives the variable declaration of result, whose value is specified by the int data type as an integer. The statement in line 5 adds the two integers represented by x and y and assigns the computation result to the result variable. The return statement in line 6 then returns the computation result represented by result.
Last, but not least, the closing brace (}) in line 7 is used to close the function.
TIP
When you create a function in your C program, don't assign the function too much work. If a function has too much to do, it will be very difficult to write and debug. If you have a complex programming project, break it into smaller pieces. And try your best to make sure that each function has just one task to do.