Search

2.2 — Function return values

Consider the following program:

This program is composed of two conceptual parts: First, we get a value from the user. Then we tell the user what double that value is.

Although this program is trivial enough that we don’t need to break it into multiple functions, what if we wanted to? Getting an integer value from the user is well-defined job that we want our program to do, so it would make a good candidate for a function.

So let’s write a program to do this:

While this program is a good attempt at a solution, it doesn’t quite work.

When function getValueFromUser is called, the user is asked to enter an integer as expected. But the value they enter is lost when getValueFromUser terminates and control returns to main. Variable num never gets initialized with the value the user entered, and so the program always prints the answer 0.

What we’re missing is some way for getValueFromUser to return the value the user entered back to main so that main can make use of that data.

Return values

When you write a user-defined function, you get to determine whether your function will return a value back to the caller or not. To return a value back to the caller, two things are needed.

First, your function has to indicate what type of value will be returned. This is done by setting the function’s return type, which is the type that is defined before the function’s name. In the example above, function getValueFromUser has a return type of void, and function main has a return type of int. Note that this doesn’t determine what specific value is returned -- only the type of the value.

Second, inside the function that will return a value, we use a return statement to indicate the specific value being returned to the caller. The specific value returned from a function is called the return value. When the return statement is executed, the return value is copied from the function back to the caller. This process is called return by value.

Let’s take a look at a simple function that returns an integer value, and a sample program that calls it:

When run, this program prints:

5
7

Execution starts at the top of main. In the first statement, the function call to return5 is evaluated, which results in function return5 being called. Function return5 returns the specific value of 5 back to the caller, which is then printed to the console via std::cout.

In the second function call, the function call to return5 is evaluated, which results in function return5 being called again. Function return5 returns the value of 5 back to the caller. The expression 5 + 2 is evaluated to produce the result 7, which is then printed to the console via std::cout.

In the third statement, function return5 is called again, resulting in the value 5 being returned back to the caller. However, function main does nothing with the return value, so nothing further happens (the return value is ignored).

Note: Return values will not be printed unless the caller sends them to the console via std::cout. In the last case above, the return value is not sent to std::cout, so nothing is printed.

Fixing our challenge program

With this in mind, we can fix the program we presented at the top of the lesson:

When this program executes, the first statement in main will create an int variable named num. When the program goes to initialize num, it will see that there is a function call to getValueFromUser, so it will go execute that function. Function getValueFromUser, asks the user to enter a value, and then it returns that value back to the caller (main). This return value is used as the initialization value for variable num.

Compile this program yourself and run it a few times to prove to yourself that it works.

Void return values

Functions are not required to return a value. To tell the compiler that a function does not return a value, a return type of void is used. Let’s look at the doPrint() function from the previous lesson:

This function has a return type of void, indicating that it does not return a value to the caller. Because it does not return a value, no return statement is needed (trying to return a specific value from a function with a void return type will result in a compilation error).

Here’s another example of a function that returns void, and a sample program that calls it:

In the first function call to function returnNothing, the function prints “Hi” and then returns nothing back to the caller. Control returns to main and the program proceeds.

The second function call to function returnNothing won’t even compile. Function returnNothing has a void return type, meaning it doesn’t return a value. However, this statement is trying to send the return value of returnNothing to std::cout to be printed. std::cout doesn’t know how to handle this (what value would it output?). Consequently, the compiler will flag this as an error. You’ll need to comment out this line of code in order to make your code compile.

A void return type (meaning nothing is returned) is used when we want to have a function that doesn’t return anything to the caller (because it doesn’t need to). In the above example, the returnNothing function has useful behavior (it prints “Hi”) but it doesn’t need to return anything back to the caller (in this case, main). Therefore, returnNothing is given a void return type.

Returning to main

You now have the conceptual tools to understand how the main function actually works. When the program is executed, the operating system makes a function call to main. Execution then jumps to the top of main. The statements in main are executed sequentially. Finally, main returns an integer value (usually 0) back to the operating system. This is why main is defined as int main().

Why return a value back to the operating system? This value is called a status code, and it tells the operating system (and any other programs that called yours) whether your program executed successfully or not. By consensus, a return value of 0 means success, and a non-zero return value means failure.

Best practice

Your main function should return 0 if the program ran normally, or a non-zero value if it encountered an error and could not complete as expected.

Note that the C++ specification explicitly specifies that function main must return an int. Some compilers will invalidly let you specify a void return type (they will implicitly return 0 if you do this), but you should not rely on this.

For now, you should also define your main() function at the bottom of your code file, below other functions.

A few additional notes about return values

First, if a function has a non-void return type, it must return a value of that type (using a return statement). Failure to do so will result in undefined behavior. The only exception to this rule is for function main(), which will assume a return value of 0 if one is not explicitly provided. That said, it is best practice to explicitly return a value from main, both to show your intent, and for consistency with other functions (which will not let you omit the return value).

Best practice

Always explicitly provide a return value for any function that has a non-void return type.

Warning

Failure to return a value from a function with a non-void return type (other than main) will result in undefined behavior.

Second, when a return statement is executed, the function returns back to the caller immediately at that point. Any additional code in the function is ignored.

Third, a function can only return a single value back to the caller each time it is called. However, the value doesn’t need to be a literal, it can be the result of any valid expression, including a variable or even a call to another function that returns a value. In the getValueFromUser() example above, we returned a variable holding the number the user typed.

Finally, note that a function is free to define what its return value means. Some functions use return values as status codes, to indicate whether they succeeded or failed. Other functions return a calculated or selected value. Other functions return nothing. What the function returns and the meaning of that value is defined by the function’s author. Because of the wide variety of possibilities here, it’s a good idea to document your function with a comment indicating what the return values mean.

For example:

Reusing functions

Now we can illustrate a good case for function reuse. Consider the following program:

While this program works, it’s a little redundant. In fact, this program violates one of the central tenants of good programming: “Don’t Repeat Yourself” (often abbreviated “DRY”).

Why is repeated code bad? If we wanted to change the text “Enter an integer:” to something else, we’d have to update it in two locations. And what if we wanted to initialize 10 variables instead of 2? That would be a lot of redundant code (making our programs longer and harder to understand), and a lot of room for typos to creep in.

Let’s update this program to use our getValueFromUser function that we developed above:

This program produces the following output:

Enter an integer: 5
Enter an integer: 7
5 + 7 = 12

In this program, we call getValueFromUser twice, once to initialize variable x, and once to initialize variable y. That saves us from duplicating the code to get user input, and reduces the odds of making a mistake. Once we know getValueFromUser works for one variable, it will work for as many of them as we need.

This is the essence of modular programming: the ability to write a function, test it, ensure that it works, and then know that we can reuse it as many times as we want and it will continue to work (so long as we don’t modify the function -- at which point we’ll have to retest it).

Best practice

Follow the DRY best practice: “don’t repeat yourself”. If you need to do something more than once, consider how to modify your code to remove as much redundancy as possible. Variables can be used to store the results of calculations that need to be used more than once (so we don’t have to repeat the calculation). Functions can be used to define a sequence of statements we want to execute more than once. And loops (which we’ll cover in a later chapter) can be used to execute a statement more than once.

Conclusion

Return values provide a way for functions to return a single value back to the function’s caller.

Functions provide a way to minimize redundancy in our programs.

Quiz time

Question #1

Inspect the following programs and state what they output, or whether they will not compile.

1a)

Show Solution

1b)

Show Solution

1c)

Show Solution

1d)

Show Solution

1e)

Show Solution

1f)

Show Solution

1g)

Show Solution

1h) Extra credit:

Show Solution

Question #2


What does “DRY” stand for, and why is it a useful practice to follow?

Show Solution


2.3 -- Introduction to function parameters and arguments
Index
2.1 -- Introduction to functions

6 comments to 2.2 — Function return values

  • Yo I am able to understand that
    int return7()
    {
        return 7;
    }

    int return9()
    {
        return 9;
    will equal 16 but I do not get why or how or what this works. PLEASE EXPLAIN

    • Alex

      When this expression statement is evaluated:

      return7() calls the return7 function, which returns the value 7. return9() calls the return9 function, which returns the value 9.

      If we plug in those intermediate values, we get this:

      Which should make it clearer where 16 is coming from.

  • Vladislav Trnka

    Sentence 'Now we have can illustrate a good case for function reuse.' does not make sense.

  • Maria

    Under the Fixing Our Program example. On line 14 isn't the semi-colon supposed to be outside the brackets. When I tried to compile, it would give me some errors

Leave a Comment

Put all code inside code tags: [code]your code here[/code]