Although it is to have more than one return statement in any C function, only one of them can be called. As soon as the first return statement is called, the function exits and other return statements will not be called. To see why, consider the example:
-
double convert_miles_to_kilometers(double mi)
-
{
-
double km; // Declare a new variable to hold the converted value.
-
km = mi * 1.61; // Conversion: 1 mile = 1.61 Km.
-
return km; // Return the value from the function.
-
-
}
-
So if main calls this function, it will have a statement such as:
-
double x; // Declare variable.
-
x = convert_miles_to_kilometers(5); // Call the conversion function.
-
printf("5 miles are %d kilometers.\n", x);
-
Note that the function contains only one return statement, which was returned to x in the second line of the second code snippet.
Now consider a block of code that contains two return statements:
-
double absolute_value(double x)
-
{
-
if (x >= 0)
-
return x; // The absolute value of a positive value is unchanged.
-
else
-
return -x; // The absolute value of a negative value is its opposite.
-
-
}
-
If main calls the function absolute_value(2.5), the if statement will be evaluated to true, so the first return statement will be called and the function will exit. If, however, main calls absolute_value(-2.5), the if statement will be evaluated to false, so the second return statement (after else) will be called and the function will exit without having called the first return statement.
Hope that answers your question.
EDIT:
If you really have to return two values from a function, such as a function that takes in a length in meters and converts it to feet and inches, return statements won't do. Instead, you may have to pass the variables feet and inches
by reference to let the function modify their address.