Search

1.4 — A first look at functions and return values

A function is a reusable sequence of statements designed to do a particular job. You already know that every program must have a function named main() (which is where the program starts execution). However, most programs use many functions.

Often, your program needs to interrupt what it is doing to temporarily do something else. You do this in real life all the time. For example, you might be reading a book when you remember you need to make a phone call. You put a bookmark in your book, make the phone call, and when you are done with the phone call, you return to your book where you left off.

C++ programs work the same way. A program will be executing statements sequentially inside one function when it encounters a function call. A function call is an expression that tells the CPU to interrupt the current function and execute another function. The CPU “puts a bookmark” at the current point of execution, and then calls (executes) the function named in the function call. When the called function terminates, the CPU goes back to the point it bookmarked, and resumes execution.

The function initiating the function call is called the caller, and the function being called is the callee or called function.

Here is a sample program that shows how new functions are defined and called:

This program produces the following output:

Starting main()
In doPrint()
Ending main()

This program begins execution at the top of function main(), and the first line to be executed prints Starting main(). The second line in main() is a function call to the function doPrint(). At this point, execution of statements in main() is suspended, and the CPU jumps to doPrint(). The first (and only) line in doPrint prints In doPrint(). When doPrint() terminates, the caller (main()) resumes execution where it left off. Consequently, the next statement executed in main prints Ending main().

Note that function calls are made by using the function name, plus an empty set of parenthesis (). We’ll talk about what this set of parenthesis is in the next lesson. For now, just note that if you forget them, your program may not compile (and if it does, the function will not be called as expected).

Rule: Don’t forget to include parenthesis () when making a function call.

Return values

When the main() function finishes executing, it returns an integer value (typically 0) back to the operating system (the caller) by using a return statement.

When you write your own functions, you get to decide whether a given function will return a value to the caller or not. This is done by setting the return type of the function in the function’s definition. The return type is the type declared before the function name. Note that the return type does not indicate what specific value will be returned. It only indicates what type of value will be returned.

Then, inside the called function, we use a return statement to indicate the specific value being returned to the caller. The actual value returned from a function is called the return value.

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

In the first function call of return5(), the function returns the value of 5 back to the caller, which passes that value to std::cout to be output.

In the second function call of return5(), the function returns the value of 5 back to the caller. The expression 5 + 2 is then evaluated to 7. The value of 7 is passed to cout to be output.

In the third function call of return5(), the function returns the value of 5 back to the caller. However, 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 std::cout. In the last case above, the return value is not sent to std::cout, so nothing is printed.

Return values of type void

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 program above:

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.

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

In the first function call to 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 returnNothing() won’t even compile. Function returnNothing() has a void return type, meaning it doesn’t return a value. However, function main() is trying to send this nothing value to std::cout to be printed. std::cout can’t handle “nothing” values, as it doesn’t know what to do with them (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.

The only valid thing you can do with void return values is ignore them.

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 positive return value means failure.

Note that the C++ standard explicitly specifies that main() must return an int. However, if you do not provide a return statement in main, the compiler will return 0 on your behalf. 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).

For now, you should also define your main() function at the bottom of your code file. We’ll talk about why shortly, in section 1.7 -- Forward Declarations.

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). The only exception to this rule is for function main(), which will assume a return value of 0 if one is not explicitly provided.

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

A function can only return a single value back to the caller. The function may, however, use any logic at its disposal to determine which specific value to return. It may return a single number (return 5). It may return the value of a variable or an expression (both of which evaluate to a single value). Or it may pick a single value from a set of possible values (which is still just a single value).

There are ways to work around only being able to return a single value back to the caller, which we will discuss when we get into the in-depth section on functions.

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 leave a comment on your functions indicating not just what they return, but also what the return value means.

Reusing functions

The same function can be called multiple times, which is useful if you need to do something more than once.

This program produces the following output:

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

In this case, main() is interrupted 2 times, once for each call to getValueFromUser(). Note that in both cases, the value read into variable a is passed back to main() via the function’s return value and then assigned to variable x or y!

Note that main() isn’t the only function that can call other functions. Any function can call another function!

This program produces the following output:

Starting main()
A
B
Ending main()

Nested functions

Functions can not be defined inside other functions (called nesting) in C++. The following program is not legal:

The proper way to write the above program is:

Quiz time

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

1.4a -- A first look at function parameters and arguments
Index
1.3a -- A first look at cout, cin, and endl

446 comments to 1.4 — A first look at functions and return values

  • jeremy

    I tried manually typing the first sample program into microsoft visual studio and got three errors, even though I checked it for errors:

    function int main(void) already has a body

    PCH warning an unknown error occured, an intellisence PCH file was not generated

    syntax error: missing ‘;’ after ‘}’

    what does this mean?

    • Alex

      int main(void) has a body means you’ve already declared a main() function somewhere else in this project. You can only have one function named main.

      I don’t know about the PCH warning.

      ; missing after } means you either forgot a semicolon somewhere, or you tried to do something that caused the compiler to get confused where it thought you should have a ; somewhere. Figure out what line it’s complaining about, and then see if there are any syntax errors on those line or the few lines before that one.

  • Levi

    I am having a hard time understanding what "the caller" is?

    • Alex

      When a function call is encountered, the caller is the initiator of the function call, and the callee is the function being called.

      If I pick up the phone and call you, I am the caller, and you are the callee. The caller initiates, and the callee receives.

      In the top example, execution begins in function main. Midway through the program, a function call to function doPrint() is encountered. main() is the caller, and doPrint() is the callee. At this point, execution of main() stops, and doPrint() begins executing.

  • Aditya

    Hey Alex! The tutorial was amazing so far! Thank you very much!

    I however have a request of you, something I have been seeing in comments all the time and something that has troubled me too.

    At the end of the Return Values of Type Void section, just put this, you will see how:

    Important Points:

    1.

    Whenever a function is called outside of std::cout (see line 9), it prints that function and then continues with the main() function. It DOES NOT print the return value even if there is one. For example, the output for the above statement will be Sentence 1 and Sentence 2 printed on subsequent lines. function() has a return value, but it is not printed.

    2.

    Whenever a function is called inside std::cout, it prints the function AND the return value of the function if it has one. For example, the above code will have the output:

    The first one.
    The second one.
    7

    I feel this might be helpful. I had to type many a program (is that correct?) with trial and error to understand this.

    Anyway, thanks Alex!

  • Liu

    return5(); // okay: the value 5 is returned, but is discarded
    I don’t understand this statement.Why the value 5 is discarded?

  • Daniel

    hallo, i still have doubts between the voids and return… it’s said that void has no return value into caller… but when i tried this Code with inserting int x = 5 (which means value) and somehow it works and no error… could you please explain?

    • Alex

      Sure. main calls printb(). printb() creates a variable named x and initializes it with value 5. Then it prints the value of x. At this point, function printb() is done, so control is returned to main. If printb() had a non-void return value, a value would be returned to main at this point (which main could use or ignore). However, because printb() has a void return type, no value is returned to main. Which is fine, because main is just calling the function, and not trying to do anything with a return value anyway.

      Consider this similar program:

      Now, printb() will return value 5 back to main. main() adds 1 and prints the result (6).

  • Umair Shahab

    Wasn’t there supposed to be a function prototype before defining the function body? i am confused.
    like this:

    void function(int x);

    then we had to define the body like:

    void function(int x)
    {
       cout << "abc";
    }

    (maybe i am mixing C and C++ together. Correct me if i am wrong)

  • Amir

    Hey Alex! There is a grammar mistake at the " Returning to main " section.

    There’s a sentence which says : "  Finally, main returns a integer value (usually 0) back to the operating system. " in 1st paragraph.

    ( " a integer " should be replaced with " an integer " )

    Tnx.

  • Angmar

    Hi
    Do you plan to cover the new C++11’s trailing return style functions?

    auto maketripple(int x) -> int {
      return x * 3;
    }

    auto fp11() -> void (*)(const std::string&) {
      return f0;
    }

  • Tunacan

    Finally, now I understand return values! Thank you so much!

  • nwee

    hello, first time learning C++ thank you very much for keeping this site up and answering questions.

    I am not fully understanding void vs int return types - does void return just mean that the return is not a value, like a number but instead is a combination of letters? Because when you have this statement:

    void valueis5()
    {
    std::cout << "the value is 5" << std::endl;
    }

    int main()
    {
    valueis5();
    return 0;
    }

    This tells main to call on function valueis5(), and the cout "the value is 5" is stored SOMEWHERE for main() to pull it right? so it was called successfully, which means that the value was stored, it’s just not numbers it’s letters, correct?? Is that the difference between void and int? If I am wrong, is there a different return type that allows me to tell main() to output values that are letters, not numbers? so then I can put maybe return alpha; and it will tell main() alpha instead of an integer?

    My second question is, am I allowed to instantiate in the same statements as when I make cout statements like this:

    void makexvalue5()
    {
    std::cout<< "The value of x is 5" << std::endl;
    int x;
    x = 5;
    }

    does this allow me to cout that x is now 5, and also tell main() internally that x = 5 if I use it as an r-value later? like for this:

    int main()
    {
    makexvalue5();
    std::cout << x + 2 << std::endl;
    }

    would this show as:

    The value of x is 5
    7

    ?

    Thank you!

    • Alex

      No. Void means the function does not return anything back to the caller at all.

      This statement:

      prints to the screen immediately. There’s transfer of values between makexvalue5() and main() here.

      You can’t instantiate a variable in the same statement that you do a cout.

      Furthermore, any variables you define inside a function are destroyed at the end of the function, so the x defined inside of makexvalue5() is unusable in main. The only way (for now) to get a value from a called function back to main is to use the return value. So makexvalue5() would have to return 5 to get that value back to main(), and main() could then do whatever it wanted with that value.

      • nwee

        Thank you for your reply. My follow up question would be why even use a void makexvalue5() that only has std::cout << "The value is 5" << std::endl;, when you can just put that statement in the int main() function?

        • Alex

          You’d only do that if you planned to call makexvalue5() from multiple places (to reduce redundancy). This lesson is more about showing you the basic mechanics, so you can learn how things work without a bunch of distractions.

  • hamza

    teacher i have a question regarding this:

    [#include <iostream>

    // getValueFromUser will read a value in from the user, and return it to the caller
    int getValueFromUser()
    {
        std::cout << "Enter an integer: "; // ask user for an integer
        int a; // allocate a variable to hold the user input
        std::cin >> a; // get user input from console and store in variable a
        return a; // return this value to the function’s caller (main)
    }

    int main()
    {
        int x = getValueFromUser(); // first call to getValueFromUser
        int y = getValueFromUser(); // second call to getValueFromUser

        std::cout << x << " + " << y << " = " << x + y << std::endl;

        return 0;
    } ]

    why doesnt the program ask for the user input or print "pick an integer" again in the last output statement is this because it is an expression?

    either way thanks for your time and thanks a lot for the effort you put into teaching!

    • Alex

      The program only asks for input when we call getValueFromUser(), which we do twice. When we do the output statement, this function is not called as part of that statement.

  • Bill

    whats the difference between

    returnNothing();

    and  

    std::cout << returnNothing();

    Isn’t one calling on the void function and another one calling to print the void function?

    • Xavier

      bruh idk but let me know if you do :p

      • Bill

        Basically, I think returnNothing() returns to the void function normally while the other one will cause the compiler to have an error since the void has no return value.

    • Alex

      The difference is that the latter case doesn’t compile. Since returnNothing() returns void, and you can’t send a void to std::cout to be printed, the compiler will complain if you try to do this.

      In the former case, the function is called, and it returns nothing back to the caller, but that’s fine. The caller just ignores the fact that there’s no return value.

  • Adam

    I just have a quick question about the return thing since I’m a little confused. If the program starts are main() that means whenever another function is mentioned inside of it, it will retrieve information and continue where it left off in main(). Secondly, what is the point in having return5() or any function return one integer other than just checking to see if the program works

    • Alex

      > If the program starts are main() that means whenever another function is mentioned inside of it, it will retrieve information and continue where it left off in main()

      Yes.

      > Secondly, what is the point in having return5() or any function return one integer other than just checking to see if the program works

      Just to show you how functions mechanics work in the simplest way possible. In reality, writing a function like that would be pretty useless.

  • himanshu

    #include <iostream>
    int return 5()
    {
        return 5;
    }

    int main()
    {
        std::cout << return 5() << std::endl;

        return 0;
    }

    WHY THIS CODE DOES NOT PRINT….
             WHILE
    THIS WORK………

    #include <iostream>
    int return5()
    {
        
        return 5;
    }

    int main()
    {
        std::cout << return5() << std::endl;
        std::cout << return5() + 2 << std::endl;

        return5();

        return 0;
    }

  • prince

    hi Alex.
    you said
    std::cout<<voidfunc();\\voidfunc() is any void function
    will give compile error because voidfunc() returns nothing so why don’t we get a clear screen instead of error.

    • Alex

      Why would you expect it to clear the screen? A function with a void return type does not return a value. It’s illegal to pass that lack of a value into std::cout.

  • umang

    Hi ,
    Please elaborate the explanation for the below mentioned question

    Regards

    1h) Extra credit:

    #include <iostream>
    int return5()
    {
        return 5;
    }

    int main()
    {
        std::cout << return5 << std::endl;

        return 0;
    }
    Hide Solution

    This program will compile, but the function will not be called because the function call is missing parenthesis. What actually gets output depends on the compiler.

    • Alex

      In this statement:

      return5 is missing parenthesis, so return5 refers to the function itself, not the value returned by a call to the function. It should be:

    • umang

      So can we refer to functions just by name and if yes than what does it mean

      • Alex

        Yes, functions have names, just like variables. The function name refers to the function itself. Most of the time we don’t use this by itself, we use the function name with parenthesis to call the function.

  • Rob

    Hi Alex. First of all thanks for your amazing work, it’s much appreciated. I’m using Code::Blocks (v16.01) and I was wondering if there was a way to get your syntax highlighting colour scheme. I’ve already downloaded the ones from the codeblocks wiki, but none of them look quite as nice as yours.

  • jenifer

    What’s the default return type of a function?

  • Zach

    Hi Alex,

    I am having a tough time with the implications/economics on why one would include a return value and why one wouldn’t want to return a value. Why don’t we always have a return value outside of main function? Why don’t we always give other functions a void type? What benefit is there to the overall program to have a return value?

    In the tutorial, could we have just as easily assigned a void return type to the return functions and returns to the void functions? Or, for example, are void types always associated with doPrint() functions?  

    Thanks in advance. Great tutorials!

    • Alex

      The answer is pretty simple: a function should have a return value when it needs to pass something back to the caller. A function should not have a return value when it doesn’t have anything valuable to return back to the caller.

      The value returned via the return statement must match the return type of the function. So functions that return an int must return an int value. Functions that return void are not allowed to return a value.

  • Chris

    You said  "it must return a value of that type (using a return " but could you use return function but you don’t return anything back to the caller or will it give a compile error

    • Alex

      I’m not sure what you’re asking here. Can you restate your question?

    • phong nguyen

      Yes, however, you can only use it for "void" type. For example, later in the lessons, you’ll learn about if/else statements. If your method has a return type of void, you can use a  return statement to break out of that method once the condition(s) has/have been met. Like this (return;) return plus a semicolon.

  • Hardik kalra

    Hey Alex ! Can U Tell Me Why Do Nested Functions not work in C++? Plz Tell Me The Reason. I want to know it !

    • Alex

      I’m not sure why they weren’t added to the language. I do know that they were considered (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0295.pdf) but it’s unclear why they weren’t included.

  • Ahtazaz Khan

    Hi Alex,i have a question about return value.We normally write ‘return 0;’ at the end of Main function.
    How to check which value is return to the Main function by the program? Whether it is 0 or something else … ???

    • Alex

      > How to check which value is return to the Main function by the program?

      You don’t want to check which value is returned to the main function, you want to check which value is returned to the operating system by the main function.

      Your IDE probably contains some way to display this. In Visual Studio, if you run your program in debug mode using “start debugging”, it’ll print something like this into the output window:

      The program ‘[13864] ConsoleApplication1.exe’ has exited with code 1 (0x1).

      • Ahtazaz Khan

        In this statement "The program ‘[13864] ConsoleApplication1.exe’ has exited with code 1 (0x1)", 1 (0*1) is the value that is returned by the main function to the operating system…?? or something else…? Actually i didn’t get your answer… Thanks Alex.

        • Alex

          That’s the value returned by the main function to the operating system. In this case, the program returned 1 instead of 0.

          If you want to see the value returned by an internal function to another internal function, you should be able to inspect that in your debugger.

  • Akshay

    If void doesn’t return anything, how in this code it returned In doPrint() to the main function?

    • Alex

      A void function doesn’t return a _value_ back to main, but the path of execution still returns to main.

      • Akshay

        I am unable to understand what are you trying to tell, please elaborate it. In the above code it returned In doPrint() output but in the below code the output doesn’t contain Hi . Why is that difference though the code looks same?

        • Alex

          The output in your quoted code should contain “Hi”. main() calls returnNothing(), which prints “Hi”. Then returnNothing() finishes and returns back to main(), where execution continues and the program ends.

    • Ram

      Inside "main()" you are just making a call to the user defined function "doPrint()"
      The "doPrint()" does not actually return a value, rather it prints "IndoPrint()" and returns to "main()" to execute next set of actions.

  • Stelios

    if void does not return a value then how in your examples does the program output A and B
    i am confused

    • Alex

      The function printA() prints the letter A and then returns no value back to the caller.

      printB() works similarly, except it prints B instead of A.

  • Martin

    What other source do you recommend me to learn C++ from, or where was your most influential step that cleansed and enhanced your C++ skills?
    Best regards, Martin.

  • My dear c++ Teacher,
    Please let me say, in programs of this lesson you suggest for Visual Studio:
    #include <stdafx.h>
    I have a comment on it: VS 2017 although runs fine with it, it is not including in drop down menu. It is including
    #include "stdafx.h"
    With regards and friendship.

  • Noah

    I’m pretty sure I understand calling. When main receives something that is defined elsewhere, the processor calls that function to define what main is trying to do and describes the variables being used in main. However, I’m lost on what voids are. A buddy of mine told me they return nothing to c, but I’m confused still. Is void just a function to define something behind the scenes of the actual function happening?

    • Alex

      You seem like you’re close, but I’m not sure you quite have it. When a function is called from main, the program puts a bookmark after the function call being made, jumps to the function being called, executes it, and then returns back to main (at the point of the bookmark) at continues executing. The only thing main receives is the return value from the called function, if there is one. void is used to indicate that the function does not return a value back to the caller.

      • Noah

        So what then is the point of a void if it isn’t going to output a value to main? I thoroughly believe there is a reason, such is the reason of a void being taught this early. I’m just not quite grasping what you would use a non-return function for. Does Main give the integer to the void function, which the void function then uses to calculate the values of the integers given by main?

        ^Update:
        From my brushing up on knowledge of what return is and what void does, my basic understanding is this. Return (Value) says if it was run successfully or not. A void returns nothing to the processor, therefore does not need a return function. voids only exist to plug variable integers in and use them in a function, and send it back to main. Tell me if I’m right, wrong, or going the opposite direction in my understanding. I think I’m closer than I was

        • Alex

          It sounds like you’re still close but not quite there.

          Two things:
          * The main() function must return an integer to the operating system, which indicates whether the application was run successfully (0 = success, non-zero = failure).
          * All other functions can choose whether they want to return a value back to the caller or not, and what the meaning of this return value is. Void is used to indicate no return value back to the caller.

          So, for example, a function that does nothing but print something would not need to return anything back to the caller (what would it return?). This function would use the void keyword as the return value, indicating no return value. A function that calculates a value based on some other values would probably want to return this calculated value back to the caller. In this case, a return value would be used.

  • Alice

    getValueFromUser, returnNothing, doPrint.
    Why do they always start with a small letter? Does it matter what the word(called function?) is? I keep getting the same result even if I used one letter(I know it may not be a good idea but I wanted to see the difference).

  • Claudio

    I know this is very simple, and that i don’t need a function to do this, but i was just trying some stuff while i was learning.

    i wanted to know why if a call suma() doesn’t give me the number that should (if I enter number 2 , 3 and 5 at the end it prints a random 6 or 8 digits number, but when i put this

    it prints 10)

    • Alex

      The problem here is that the a, b, and c inside main are separate from the a, b, and c inside suma() (despite using the same names). The values the user inputs into main’s a, b, and c aren’t transferred to the a, b, and c inside suma().

      If you want those values to transfer (and given the structure of your program, you do), you should pass a, b, and c as arguments to suma() instead of having suma() define a, b, and c inside the function body. We cover how to do that in the next lesson.

      • Claudio

        thanks! I wask kinda short of time, so I read this one and ask that, and now I’m going to keep going, sorry about that.

        By the way… this page is just great! and you be solving this problems after all this years… WOW you’re awesome.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter