Creating Functions That Return a Value

The final addition to making your functions as practical as the standard C library functions is to have them return values. This is accomplished using the return statement, which you've already been using in the main function. You can return any single value from your function:

return 1;

The returned value can even be based on a variable's value:

int num = 8;
return num;

Any function that returns a value must have a proper prototype and definition, both of which must indicate the type of value returned. You've already seen this with the main function (which returns an int). Here's another sample function definition:

int my_func (void) {
   return 27;
}

You can assign the returned values to variables when the function is called, use them in calculations, or even use them as the argument to another function:

number = my_func();
sum = num + my_func();
printf("A number: %d", my_func());

This next example will take an integer and return its factorial. In case you don't remember from the previous factorial example in Chapter 4, “Control Structures,” the factorial is represented in math as n! and is equal to every number from 1 to n multiplied together (so 4! is equal to 1 * 2 * 3 * 4).

To define and use your own functions that return values

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 7.3):

/* return_factorial.c - Script 7.3 */
#include <stdio.h>

Script 7.3. The return_factorial() function returns the factorial value of a submitted integer.


3.
Add the function prototype:

unsigned long long int
 return_factorial (unsigned int
 num);

The function being defined in this file is called return_factorial. This function takes one argument, an unsigned integer that will be assigned to num. The function also returns an integer value, as indicated by the initial int in the function prototype. Because factorials can quickly become quite large, an unsigned long long int will be returned, which is acceptable in the C99 standard.

4.
Begin the main function:

int main (void) {

5.
Declare the required variables:

char input[3];
int number;

The application will take a user-submitted number and calculate the factorial of that. Therefore, one integer variable is necessary and a character string will be used to read in the input.

6.
Prompt the user:

printf ("Enter a positive integer
 for which the factorial will be
 calculated: ");

Be certain in your prompts to indicate to the user what type of information is expected (Figure 7.5). It doesn't guarantee that the user will submit that type, but it helps.

Figure 7.5. The application first prompts the user to indicate what kind of input is expected.


7.
Read in the input and assign it to the number variable:

fgets (input, sizeof(input), stdin);
sscanf (input, "%d", &number);

The fgets()-sscanf() method of reading in numbers was introduced in Chapter 5, “Standard Input and Output,” as a safe technique. You can review the instructions there if you are confused about the syntax.

8.
Validate the number:

if (number > 0 ) {

To ensure that the number is a positive integer, a conditional is used before calling the return_factorial() function. If this condition is true, the factorial can be calculated. If it is false, the user will be notified of the error.

9.
Call the return_factorial() function and print the result:

printf ("The factorial of %d is
 %lu.
", number, return_factorial
 (number));

This print statement prints the original value and the factorial value. Instead of calling the return_factorial() function and assigning this to another variable, the value is returned as an argument to the printf() function.

In the print statement, the %lu signifier is used for the factorial value, because this is an unsigned long long integer.

10.
Complete the conditional:

} else {
    printf ("You must enter
 a positive integer!
");
}

This statement is executed if the number is not greater than 0. The error message (Figure 7.6) lets the user know a problem occurred.

Figure 7.6. If the user does not enter an integer greater than 0, an error message is printed.


11.
Complete the main function:

    getchar();
    return 0;
}

12.
After the main function, begin defining the return_factorial() function:

unsigned long long int
 return_factorial (unsigned int
 num) {

This definition mirrors the function prototype, indicating that one unsigned integer value is expected and another is returned.

13.
Define the required variables:

unsigned long long int sum = 1;
unsigned int i;

Along with the number submitted to the function, this function needs two more integers: sum, which will total up the factorial, and, i, a counter for the loop.

14.
Calculate the factorial:

for (sum = 1, i = 1; i <= num; ++i) {
    sum *= i;
}

This code comes from the factorial example in Chapter 4. It creates a sum by multiplying every number up to and including num (the submitted number) together.

15.
Return the calculated value and complete the function definition:

    return sum;
}

The final step in this function is to use the return statement to return the calculated sum.

16.
Save the file as return_factorial.c, compile, and debug as necessary.

17.
Run the application (Figure 7.7).

Figure 7.7. The factorial of a user-entered number is calculated and returned using a user-defined function.


✓ Tips

  • The return_factorial example primarily focuses on demonstrating how to return values from functions. There are several improvements you could make to polish it, such as discarding extraneous input, confirming that the submitted value is a number (the application will calculate the factorial of S, if given the chance), and checking that the factorial value does not go out of range.

  • Some programmers think it's best to have only one return statement within a function, but C allows you to have multiple statements. Only one return statement will ever be executed, though. A common example is something like

    if (condition) {
         return 1;
    } else {
         return 0;
    }
    
  • The return statement stops the execution of a function so if you have any code after an executed return, it will never be executed. This applies within a specific code block, like this:

    if (condition) {
         return 1;
         /* This line won't be executed
     if the condition is true. */
    } else {
         return 0;
         /* This line won't be executed
     if the condition is false. */
    }
    
  • To be really formal, you can use

    return;
    

    as a line in a function that returns no values.

  • You cannot return multiple values from a function in C. You can simulate this effect using pointers, however. You'll learn about pointers in Chapter 9, “Working with Pointers.”


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset