Functions that Return a Value
So far we have looked at functions that do not compute a value. We declare these to have the void return type.
In many cases, we WILL want to define functions that can be used to compute values. By declaring a function as having a return type other than void, we are declaring it as computing that kind of value if it is used in an expression.
Examples:
Function name | Information needed | Parameters | Result computed | Return type |
---|---|---|---|---|
sumRange | min and max values of range | int min, int max | sum of integers in range | int |
factorial | value to compute factorial of | int value | factorial of value | int |
isOdd | an integer value to test | int value | whether or not the value is odd | int (really boolean) |
sqrt | a double value | double value | square root of value | double |
Function calls
Compute the factorial of 13:
int result;
result = factorial(13);
printf("factorial of 13 is %i\n", result);
What is happening?
Compute the sum of a range of integer values entered by the user:
int min, max, sum;
scanf("%i %i", &min, &max);
sum = sumRange(min, max);
printf("sum is %i\n", sum);
If the user’s age is odd, print a message:
int age;
scanf("%i", &age);
if (isOdd(age)) {
printf("your age is odd\n");
}
Implementing Functions that Return a Value
Return statements
In functions that compute a value, a return statement is used to specify the result of performing the computation. As soon as a return statement is reached, the indicated value is returned, and used as the value of the function call expression at the call site.
Examples:
sumRange function:
int sumRange(int min, int max) {
int sum = 0;
for (int i = min; i <= max; i++) {
sum += i;
}
return sum;
}
isOdd function:
int isOdd(int value) {
if ((value % 2) == 1) {
return 1;
}
else {
return 0;
}
}
Important: It is critical that when you write a function that returns a value, it is guaranteed to return a value. For example, consider a buggy version of isOdd:
int isOdd(int value) {
if ((value % 2) == 1) {
return 1;
}
}
This version of isOdd does not return a value if the parameter is even. When the program runs, if an even value is passed to the function, the value returned by the function will be unpredictable, and strange behavior may result.
Testing
It is very important to test your functions to make sure they work correctly.
One way to test is to use some logic with printf’s to check that functions are returning the expected value for particular input. Note: be careful when checking floating point numbers for equality as roundoff errors can occur. For example, to test the factorial function
#include <stdio.h>
int factorial(int value);
int main(void) {
if (6 == factorial(3)) {
printf("Test passed 6 = %i\n",factorial(3));
} else {
printf("Test failed\n 6 != %i\n",factorial(3));
}
return 0;
}
int factorial(int value) {
...
}