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 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 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 the return value is discarded.

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 a 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()
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.


Show Solution


Show Solution


Show Solution


Show Solution


Show Solution


Show Solution


Show Solution

1h) Extra credit:

Show Solution

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

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

  • winston

    why do i need to put “endl” at the end of somethings? It tells me too but when i dont it still works.

  • andrew

    Hi people . i mixed it up a bit with this lession . used bits from the last couple of lessions. which made it interesting . sorry if somone else posted somthing like this dident read all the comments.

    heres what i came up with .

    ps learning heaps thanks for the site .

    • Gizmo

      Hello, Andrew

      doprint() serves no purpose here.

      This would be easier to read and write.

  • Andrew Chmielewski

    when I click build it says it “succeeded” but it doesnt open up the run window to show it. What is wrong?

  • lsandling

    I have this really wacked question I must have missed something I can’t find Why don’t we put “using namespace std;” on the very top like right after our #includes ?

    • Alex

      If you did that, the using statement would apply to the entire file. That’s generally considered bad practice.

      By declaring it inside of a function, you limit the effect of the using statement to just the function, which is safer.

  • jack

    I already know Javascript and some normal Java but this is not responding to things like ‘cin’ and ‘end1’ in the ‘iostream’ library. Why?

  • Josh

    Do you always have to put all your functions above the main function?

  • Alex

    im writeing down for example “In DoPrint” bewten the cout and endl but i get red letters insteed of blue ones?? why?? im using visual c++ 2010
    i have done everything right

  • Jubjamie

    i have tried the following example in the tutorial but it just doesn’t work., What have missed?

  • db_z

    does cout mean ecout like in French

    • Dino

      I really hadn’t thought of that. Nice.
      Unfortunately Mr. Stroustrup (our beloved c++ father πŸ™‚ ) is not as romantic. cout is simply (c)haracter (out)put

  • JPL

    Very well explained thanks for these tutorials:) Here is my first program using functions.

  • buck

    Hi Alex,
    Just wanted to add my thanks for a great tutorial.

  • Damien

    Hi Alex,
    Your tutorials are amazing and im going through them and understanding every bit. But where do i put this code?

    Let’s use these functions in a program:

  • Mike

    My code is exact same as his yet i get an end1 undeclared identifier error
    any reasons why? and i dont know to to do those tags but i did include the iostream thing and #


    void DoPrint2()
    using namespace std;
    cout << “In DoPrint2()” << end1;
    void DoPrint()
    using namespace std;
    cout << “starting DoPrint()” << end1;
    cout << “Ending DoPrint()” << end1;

    int main()
    using namespace std;
    cout << “Starting main()” << endl;
    cout << “Ending main()” << end1;
    return 0;

  • joe

    is it normal for my ms-dos window to close right after i put in a number and press enter

  • Dude, just declare

    before the functions! It works for me. Thanks πŸ™‚

  • Darrell

  • Ravi

    Alex Sir,

    I have been observing that whenever you are calling a function,
    the function been called has been declared earlier in the program.
    Is there any specific reason that a function been called has to be
    present before it is been called…

    I mean to say that,

    If i call a function named “doprint2()” from a function;
    “doprint1()” and the function “doprint1()” has been coded before
    the function “doprint2()”. And then, i call the function would it affect
    it anyway..

    • A function must be declared prior to it’s use. However, it does not necessarily need to be defined before use.

      In all these examples I declare and define the functions before they are used because it keeps the examples easy. However, in future lessons, you will learn how to prototype a function so you can both use it and define it anywhere you want.

  • adam

    If you define the value of x then call a different function will it remember the value of x? Because when I compile my infinitely increasing number loop I get this error:

    Here’s the source code:

    • No. If a variable is declared in one function, other functions won’t even know it exists unless you pass it as a parameter.

      The reason you are getting an error is because x is declared in main(), so loop() is unaware of it’s existence.

  • Jose

    c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(19) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(19) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(20) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(20) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(21) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(21) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(25) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(25) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(27) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(27) : error C2065: ‘endl’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(28) : error C2065: ‘cout’ : undeclared identifier
    1>c:documents and settingsjosemy documentsvisual studio 2008projectsfunctionsfunctionsfunctions.cpp(28) : error C2065: ‘endl’ : undeclared identifier
    1>Build log was saved at “file://c:Documents and SettingsJoseMy DocumentsVisual Studio 2008ProjectsFunctionsFunctionsDebugBuildLog.htm”
    1>Functions - 12 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Any help?

  • Seltox

    I’ve gone through quite a few websites looking for tutorials.

    This one is by far the best i’ve ever seen.

    Alex, you are an amazing teacher. Everything here is clear, and the examples let you put it into practice, give you a template to do your own things with, and the quiz at the end is an excellent self-learning tool to make sure you actually know what you think you do.

    Only suggestion I could make would be to perhaps put a few more quizzes into pages that don’t have one πŸ˜‰

    Thanks so much. I’ve been wanting to learn C++ for probably 2 years now. I’ve always had the motivation, but I could never find a tutorial that could get me over that first little step (past the Hello World! program ;)).


    • I appreciate your comments. I’d definitely like to go back and add more quizzes to the pages that don’t have them, and add more quiz questions to the pages that do. I’ve been prioritizing new content over quizzes, but now that I’m almost done with the initial content set (just have exceptions to do) I will hopefully have time for that soon. Thanks again.

      • Big"B"LuvRRR

        Hmmm, looks like you’ve *taken out* quizzes, too -- from this lesson, anyway!  Folks seem to refer to quizzes here that are no longer available…what’s happened to ’em, please???  Can be rather confusing reading comments when they refer to things no longer on the webpage….

        • Alex

          What actually happened was that the lesson was getting too long, so I split it into two parts. The quiz moved into the second part. When I split a lesson, I’ll try to match the comments with the correct part of the lesson, but it isn’t always possible.

  • Stefan

    Thank you so much. This tutorial is definitely the best out there!

  • Rousseaux

    i’d like to see my previous comment w/ my .c proggie and how ppl rate it. Noobs need reinforcement

    PS i’m glad you mentioned “less than/greater than” is not a c++ operator, i couldn’t figure that one out though it would be cool if it worked. Can i # define it and add it to “iostream”?

    • Unfortunately, you can’t define <> as a new operator in C++. If you’re looking to do inequality (which is the only thing I can think of that would make sense for <>), you’ll have to get used to using !=

      • Rousseaux

        Nah, the way i saw that operator, , used was to define get a variable (for example from cin, and cout that variable. As Frostbite and Sumanyu did above.

  • Frostbite

    After studying your first couple of steps over night this is the code I managed to compile. Mind you I just started last night and never knew a thing about coding until now. I put did a combination of the three tests and heres what I came up with. It was very much enjoyable debugging and learning that the void must come before the main. Only takes one mind to expand a thousand others, thanks Alex much appreciated, cant wait to study further!

    // Test subject.cpp : main project file.

    #include “stdafx.h”

    using namespace System;

    void Test()
    using namespace std;
    cout << “Starting Test 2” << endl;

    cout << “What is the value of X x Y?” <> x;
    cin >>y;

    cout << “The correct answer is ” << x + y <<endl;

    cout << “Testing complete!” <<endl;

    system (“pause”);

    int main()
    using namespace std;
    cout << “Test 1 compiling…” <<endl;

    cout << “Compiling complete, starting Test2” <<endl;

    system (“pause”);


    return 0;


    • Frostbite

      somehow in the transferring this typo came up:
      cout << β€œWhat is the value of X x Y?” x;
      should read:
      cout << “What is the value of X + Y?” <>y;
      cin >>x;

      not sure how to embed the code to make it look proper yet, so its still not working apparently

  • I come from a pretty decent background. I have had 7 years experience in my overall field. I know PHP/Javascript like the back of my hand…I wanted to get into C++ lately and I am working towards it. So far I love the language. The ONE thing I don’t like so far about it is having to put the main function at the bottom (or the other way you mentioned). It seems kind of unnecessary and definitely doesn’t sound like it’ll be very neat and manageable. The hard part is remebring to make a function before that…the one problem I would have is if I had 2 functions that called each other.
    In PHP you can have 1 function and then another function and because they are related sometimes each one of the functions ends up calling the OTHER function once. So that leaves you with something you can’t do in C++. You can’t make both functions above each other (impossible) so it won’t work like that.

  • sony

    what is the difference between the following declarations
    void show()and void show(void)

  • Jefferson

    I think these are absolutely great tutorials, certainly the best I’ve ever found. Please keep up the great work Alex!

    I feel silly saying this, since I’m just starting out, but shouldn’t quiz questions one through three have
    using namespace std;
    statements in their main functions since they use cout and endl?

    • Thanks for the complements, and your question isn’t silly at all. If you wanted to compile these fragments, you’d need to add using namespace std; as well as #include <iostream>, but since they’re just code fragments rather than entire programs meant to be compiled I omitted the minor details.

  • Person In Need

    Why is this not working?

    Ignore the include blank thing, I dont know why its doing that, I have iostream after that, this thing keeps erasing it..

  • Abhishek

    Fox is right πŸ™‚

  • Fox

    These tutorials are fantastic :]

  • I noticed you include this comment we need this in each function that uses cout and endl when you include namespace std;.

    Why do you include the library locally as opposed to globally? Are there functions in the library that conflict with other libraries that would cause a problem? Is it just a matter of preference? I hope I am not getting ahead of myself here.

    • That’s a very good question, actually.

      Just as with local/global variables, it’s better to declare things at a local scope if you can (and it’s not too onerous). It reduces the chance of inadvertently changing something you didn’t mean to, or having a name clash.

      While this is rarely a problem in small programs, in gigantic programs that run ten or hundreds of thousands of lines of code, your odds of having a strange name clash go up significantly.

      Probably the safest solution is to not use a “using” statement at all, and explicitly call the function with it’s namespace qualifier:

      std::cout << "Hello world!" << std::endl; But that makes for some ugly, harder to read code (and I haven't covered the scope qualifier yet!). Using a using statement at the function level is a nice compromise between safety and readability.

      • Claimcpp

        Well, in this case, can’t we merge libraries together? and then obviously if u can do that the computer will automatically detect duplicated function names, even if it can’t, you would manually be able to sort it out

        • Alex

          Generally you won’t want to merge libraries together. Libraries are generally designed to provide a set of functionality to do a specific job. Say for example you have a math library, and a sound library. It wouldn’t really make sense to put them together. And even if you did, it wouldn’t resolve the naming conflict (you’d just move the naming conflict into the library itself instead of in your program).

      • Syed

        Hi Alex,
        Thank you very much for this website which is no doubt best in the world for learning C++.
        I have a question about std::cout, when I run this code it print 0 as well.

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

        int Hello()
           std::cout<<"Hello World"<<std::endl;
           return 0;
        int main ()
           return 0;

        I know that if I dont call the function Hello() in cout it wont print the returned 0, but any other solution.

        Thank you

        • Alex

          does two things:
          1) It calls the Hello() function.
          2) It prints the return value from the Hello() function.

          The Hello() function prints the string “Hello World”, and then it returns the value 0, which main() prints.

          There are two things you should change:
          1) Function Hello() should not have a return type of int (it should have a return type of void, since this function does not need to return anything to the caller).
          2) Function main() should not print the return value of Hello(). A simple call to Hello() will suffice.

          • Imnoob

            #include <iostream>

            int dprint(){
            std::cout<<"welcome to he menu"<<std::endl;
            return 0;

            int main() {
                std::cout<<"print the menu"<<std::endl;
                std::cout<<"end of menu";
                // your code goes here
                return 0;
            This code did not print 0 as mentioned by above fellow Nd as explained by you. What’s wrong in it plz tell.

        • Ergo

Leave a Comment

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