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.

A void return type (meaning nothing is returned) is typically 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 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

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

  • Eddie

    Hey Alex! Great website, started reading it last night and I really enjoy it, I've just started coding and this is really helping me out!

    I do have a question thought! In your example above, this code here:

    Wouldn't this be 'more correct' if you actually used

    Wouldn't the void function be a better fit in this example because you do not need to return a specific value? Int is an integer right? But we don't need to call an integer we just want to call the foo() function to print the text "foo!".

    I tried both codes and it also works using void, like this:

    I understand WHY you wrote it because you first made an example of how NOT to write, and how to write it correctly, I'm just wondering because if I'm right it means I've actually learned something haha!

    So basically if a "real" programmer was to use this in his code, would he prefer using void over int in this particular example?

    Thank you!

  • William Osler

    If you like the content, click on a few ads to support this guide.

    Appreciate the attention to detail in this guide. Thanks Alex.

  • Qbert

    Hello,

    In the examples, the code calls a function in the same line as the std::output line, i.e.:

    Of course, return5() is a very simple function. Can this be done with more complex functions? If so, have I just done it incorrectly in the code below?

    When the code below gets executed, it runs the getNumber() function before any of the output code. Is this because it tries to evaluate the line as a whole, sees that it needs to evaluate getNumber(), executes getNumber(), and THEN runs the content of main(), inputting its earlier evaluation of getNumber()?

    • nascardriver

      Hi Qbert!

      > Can this be done with more complex functions?
      Yes, but mixed std::cout and std::cin can get confusing.

      > it runs the getNumber() function before any of the output code
      That shouldn't be the case, try using std::cerr instead of std::cout to make sure the text gets printed as soon as possible.

    • Alex

      Function calls have higher precedence than operator<<, so the function call goes first.

      Per nascardriver's suggestion to use std::cerr, std::cerr really shouldn't be used for standard output -- only for error information. That way, if std::cerr is rerouted to a file, or some other output stream, your standard output won't go missing.

      If you want the text to get printed first, the best way to do that is to split your output into two lines: text first, then the function call.

      • nascardriver

        > Function calls have higher precedence than operator<<, so the function call goes first.
        Did you test this? For me the string gets printed first, I confirmed this behavior by analyzing the binary. This is the rebuilt @main based on the disassembly:

        Obviously the string gets printed before the function is called.

        > std::cerr really shouldn't be used for standard output
        True that. I only suggested it, because std::cerr flushes the buffer immediately. I was worried his output may be delayed.

        EDIT:
        I just did a quick search. It seems like the evaluation order is undefined. So:
        > If you want the text to get printed first, the best way to do that is to split your output into two lines: text first, then the function call.

        • Alex

          Yes, I tested it (on Visual Studio), looked at the order of execution in the debugger, and reconfirmed the operator precedence. In lesson 3.1, it's clear that Function call (group 2) takes precedence over operator <&lt, which is in group 7.

          My guess is that your compiler probably optimized the code so that it wouldn't have to store the result of the function call as an intermediate value.

  • kartik

    Sorry This is not programming related question but i need to know there is site for c# just like this where concept is written in very practical way but i m not able to find it anymore, i just remember that its state that you are at point a and you need to go point b in c# development something like this on its homepage, i know this is super dumb thing to ask but if you find that site please help me

    • nascardriver

      Hi Kartik!

      There's a long list of C# tutorials here https://stackify.com/learn-c-sharp-tutorials/
      Maybe you recognize the design of the page.

  • Arntzen

    Why does it matter whether or not you put "std::cout" when calling on the function "void printA()" inside "int main()"?
    It just doesn't work because you have "std::cout" double up? I don't get it.

    Second question: Why does it even output anything at all? I thought the "void" return type didn't send anything back to main and when something that wasn't in main wasn't returned to the OS.
    Is it just that number-values and not letters need a return statement and can't be used inside a function with return type "void"?
    If so, can you still return words or letters with a return statement at the end or will it give you an error?

    Thanks in advance. Love that this website is free 😀

    • nascardriver

      Hi Arntzen!

      std::cout expects data after the <<.
      Since @printA doesn't return any data (it's a void) std::cout doesn't know what to do and you get a compiler error.

      • Arntzen

        Ok, but why put anything inside function printA then? Since it's a void it doesn't return any data, doesn't that mean that nothing gets printed as well since I thought it ONLY displayed or printed something from "main"-function or do I mix up something now?

        • nascardriver

          You're mixing something up. You can print from anywhere.

          • Arntzen

            Ok. Do you have any idea what I might be mixing up?

            • nascardriver

              Nope, sorry, I can't think of anything that fits what you described.

              • Arntzen

                That's fine, I probably get reminded whenever I get more experience and learning 😀

                • Alex

                  std::cout does the printing -- and you can do this from any function you like (main or otherwise). For example:

                  The above program prints "AB". main() prints 'A', and printB() prints 'B'.

                  Here's another variant:

                  In this program, main() prints 'A'. Then doSomething() is called, which prints 'B' itself. The char 'C' is returned from doSomething() back to main(), and main() prints the return value of 'C'. So this program prints "ABC".

                  This uses a couple of concepts we haven't talked about yet, so if you're having a hard time following this, keep reading.

                • Arntzen

                  No, I totally got it. "char" = character, right?

                  The code is written on 2 seperate lines, but it prints it on the same line, that is because it hasn't "std::endl" right?

                  But the void return type, does it ONLY print integer numbers?

                  Thanks for all the support, by both of you.
                  So greatful.

    • nascardriver

      I can't reply to your newest comment, because there have been too many replies, I'll keep going here.

      > "char" = character, right?
      right

      > The code is written on 2 seperate lines, but it prints it on the same line, that is because it hasn't "std::endl" right?
      right

      > But the void return type, does it ONLY print integer numbers?
      The return type has nothing to do with console output. You can print nothing, text, numbers, characters, all you want from any kind of function.

      • Arntzen

        Ok. I don't remember if this stands somewhere in the text itself, but do where are the usecases for "void" then, what is so special about void and what does it mean to not return to main other than it not returning the function to main?

        • nascardriver

          A void function is used to do something that you don't need know anything about afterwards. A simple example is a printWelcome function:

          You'll encounter many more situations which require a void function.

          • Arntzen

            Let's use your example, could you not use e.g "char" return type instead of "void" and still get the same result (just add "return ..")?

            • nascardriver

              You could, but your executable will get bigger and your program slower. If you don't want to return anything then you don't return anything.

              • Arntzen

                Ok, so that is like the main point of "void"? If you don't HAVE TO return it since it just gonna print something  for example, it makes the executable faste. Well, that's nice.
                Thanks 😀

  • Ali Mert

    Calculator with functions :

    #include "stdafx.h"
    #include <iostream>
    int a;
    int x;
    int y;
    int z;
    int divide()
    {
        a = x / y;
        return a;
    }
    int substract()
    {
        a = x - y;
        return a;
    }
    int multiply()
    {
        a = x * y;
        return a;
    }
    int add()
    {
        a = x + y;
        return a;
    }

    int main()
    {
        
        std::cout << "Enter first integer";
            std::cin >> x;
            std::cout << "Enter second integer";
            std::cin >> y;
            std::cout << "pick one : 1 = *   2  = /  3 = -  4 = +";
            std::cin >> z;
        if (z == 1)
        {
            multiply();

        }
        if (z == 2)
        {
            divide();

        }
        if (z == 3)
        {
            substract();

        }
        if (z == 4)
        {
            add();

        }

        std::cout << "The answer is " << a;
        std::cin >> a;

        return 0;
    }

    end of code

  • Ammaar

    [#include "stdafx.h"
    #include <iostream>

    int main()
    {
        int x;
        int y;
        int z;
        
        std::cout << "Enter first integer here:";
        std::cin >> x;
        std::cout << "Enter operation (1:Addition, 2:Subtraction, 3:Multiplication, 4:Division)";
        std::cin >> y;
        std::cout << "Now enter your second integer:";
        std::cin >> z;

        if (y == 1)
        {
            std::cout << x << " plus " << z << " equals: " << x + z << std::endl;
        }

        if (y == 2)
        {
            std::cout << x << " minus " << z << " equals: " << x - z << std::endl;
        }

        if (y == 3)
        {
            std::cout << x << " times " << z << " equals: " << x*z << std::endl;
        }

        if (y == 4)
        {
            if (z == 0)
            {
                std::cout << "Please enter z again" << std::endl;
                std::cin >> z;

            }
            if (z == 0)
            {
                std::cout << "Your out of tries, sorry. :,(" << std::endl;
                    return 0;
            }
            std::cout << x << " divided by " << z << " equals: " << x / z << std::endl;

        }

        if (y <= 0)
        {
            std::cout << "You had one job and you failed" << std::endl;
        }

        if (y > 4)
        {
            std::cout << "You had one job and you failed" << std::endl;
        }
        return 0;
    }
    ]

    I made my own calculator. My first successful project.

  • Caleb Trapp

    Hi, I was wondering if you could clear something up for me. For performance, or documentations sake, is it better to call all or most of your functions in main in the order they will be executed, or call the first function you need in main, and then call the next one in the function already called?

    Example:

    In this example, SomeFunc is called, executes, and goes back to main. Then the next func is called within main, executes, and then the program ends.

    In this example, SomeFunc is called in main, executes and then instead of going back to main, the next function is called from SomeFunc.

    These two programs seem to function identically when executed, but I'm wondering two things. Is there (A) any performance reasons why one is better than the other. (B) any documentation or readability reasons why one would be better than the other for someone to read

    Or does it not matter? Either way it would be nice to know so I don't structure my programs in a way that might be less advantageous than another.

    • nascardriver

      Hi Caleb!

      (A)
      I suppose version 1 of your program is faster or at least more memory friendly (Lesson 7.9 The stack and the heap).
      The difference is so diminutive that it's nothing to worry about though.

      (B)
      It really depends on the program you are writing.
      Here's an example, because I don't know how the explain it.

      • Caleb Trapp

        So performance doesn't really matter in this case, and it's more about the context of the function and what they do? Okay, thanks for clearing that up!

        • Alex

          In my view, the former solution is significantly better than the latter. From a performance perspective, it probably doesn't matter. However, there are big differences from a dependency perspective.

          In the former program, both someFunc() and someOtherFunc() are completely independent. Your main function can call either function in any order it wants. If later on, you have some need to call someFunc() by itself, you can.

          In the latter program, someFunc() calls someOtherFunc(), which means your program can't have just the functionality of someFunc() without getting someOtherFunc() too. This is an unnecessary dependency (someFunc() is only calling someOtherFunc() because main wants it to, not because it needs to) and it reduces the flexibility of your program.

  • int getvaluefromuser()
    {
    std::cout<<"Enter an integer:";
    int a;
    std::cin>>a;
    return a;
    }
    int main()
    {
    int x=getvaluefromuser();
    int y=getvaluefromuser();
    std::cout<<x<<"+"<<y<<"="<<x+y;
    return 0;
    }
    This program is showing error in dev c++ as 'getvaluefromuser' was not declared in this scope
    What is the reason to come like this??
    Please clear my doubt

    • nascardriver

      Hi Dhiviya!
      Your code is working for me.
      Do you have any other files in your project?
      Also, please use code tags in your next post, don't use all lower case and use some spaces.

  • solhomo

    #include <iostream>
    int return5()
    {
        return 5;
    }
    int main()
    {
        std::cout << return5 << std::endl;
        return 0;
    }
    why i get 1 when it runs

  • Kolin

    Using Visual Studio this has no errors but it will not build.

    Also, adding std::cin.ignore(32767, '/n'); says that it expects an expression

    int getvaluefromuser()
    {
        std::cout << "enter an integer" << std::endl;
        int a
        ;std::cin >> a;
        return a;
    }

    int main()
    {
        int x = getvaluefromuser();
        int y = getvaluefromuser();

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

        return 0;

    • Alex

      What do you mean it won't build? It compiles but won't link into an executable?

    • Gale

      Ik old post, but to answer your question, looks like it compiles (and thus would build) just fine so long as you add your header and close bracket at the end. Should look like this in MS VSC17:

      #include "stdafx.h"
      #include <iostream>
      using namespace std;

      int getvaluefromuser()
      {
          cout << "enter an integer" << endl;
          int a
          cin >> a;
          return a;
      }

      int main()
      {
          int x = getvaluefromuser();
          int y = getvaluefromuser();

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

          return 0;
      }

      Does that work?

  • Cristiano Guerreiro

    My calculator.

  • James Smith

    Regarding the extra credit problem. I like this problem because it requires us to use the google. I had to do a little googling to understand why the program compiles without warnings or errors.

    The program compiles because the compiler sees no errors. The syntax is OK. The logic is OK. Everything is OK. In fact the program seems to be designed to test if a function named return5 was defined (without calling the function). Or maybe the user wanted to print the address of the function retur5() and needs some help.

    Here is result of my research.

    When users click Show Solution they won't find any explanation why the program compiles. They need to understand that compilers can't catch all human mistakes. I think the users should know why the program compiles. At least you could mention pointers in the Show Solution text. Or maybe there is no need to do anything. Those who really want to learn will want to understand. Their curiosity should drive them to search for answers.

  • African

    Hello Alex, Today I tried to make a basic, mini calculator and I was having trouble outputting the result of the inputs, maybe you can help me and tell me how to fix it, please. 🙂

    • Hi

      you need to use "if" condition for this type of stuff

      something like

    • Alex

      You have a good start. You've got functions to ask the user for inputs. Your program is well structured so far. But then all you do is print the inputs and the user-entered operator. At no point do you actually do any calculation. You need one more function that takes the two inputs and the operator and returns the result of the calculation (which main can then print).

    • Kaif Ahsan

      Hi, can you please explain the function of this chunk of code at the end of your program?
          

      • Alex

        std::cin.clear() clears any previous errors that have occurred, so the next std::cin statements will work properly.
        std::cin.ignore(32767, '\n') discards up to 32767 character (or until a '\n' character is found) inside std::cin. In practical terms, this gets rid of any input that was entered but not used yet.
        std::cin.get() tries to get the next character from std::cin. Because we cleared out all of the characters in the previous line, there aren't any left. Therefore, it has to ask the user to enter one. We use this as a way to pause the program.

Leave a Comment

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