Using Return Values

Summary: Function return values are often assigned to variables.

A function's return value can be used in the same way you would use any value of its type. In the VOLUME.C program from Chapter 1, “Anatomy of a C Program,” the statement that calls sphere assigns the function's return value to the variable volume:

volume = sphere( radius );

If there's no need to save the return value, you can use it directly. You may have noticed that the variable volume isn't really needed in the VOLUME.C program, which simply prints the variable's value and ends. Most programmers would make the program more compact by replacing the two statements

volume = sphere( radius );

printf( "Volume: %f\n", volume );

with this one:

printf( "Volume: %f\n", sphere( radius ) );

The second version puts the sphere function call right in the printf statement, eliminating the superfluous variable. Instead of assigning the return value to a variable and passing that variable's value to printf, the statement uses the value directly. (The sphere function is called first. Then the return value from sphere is passed as an argument to the printf function.)

While this change streamlines the program, it also makes the code a little harder to follow. If you don't read carefully, you might overlook the fact that the printf function call contains another function call.

Summary: Unused return values are discarded.

Occasionally, you may have no use for a function's return value. The printf function, for example, returns the number of characters it displayed, but few programs need this information. If you don't use a return value, it's discarded.

You should never ignore the error codes that library functions return to show whether the function succeeded. For more information about library function return values, see “Failing to Check Return Values from Library Functions”.