Search

2.1 — Introduction to functions

In the last chapter, we defined a function as a collection of statements that execute sequentially. While that is certainly true, that definition doesn’t provide much insight into why functions are useful. Let’s update our definition: 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 when it is run). However, as programs start to get longer and longer, putting all the code inside the main function becomes increasingly hard to manage. Functions provide a way for us to split our programs into small, modular chunks that are easier to organize, test, and use. Most programs use many functions. The C++ standard library comes with plenty of already-written functions for you to use -- however, it’s just as common to write your own. Functions that you write yourself are called user-defined functions.

Consider a case that might occur in real life: you’re 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 the place you bookmarked and continue your book precisely where you left off.

C++ programs can 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 ends, the CPU returns 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.

An example of a user-defined function

First, let’s start with the most basic syntax to define a user defined function. For this lesson, all user-defined functions (except main) will take the following form:

void identifier() // identifier replaced with the name of your function
{
// Your code here
}

We’ll talk more about the different parts of this syntax in the next few lessons. For now, identifier will simply be replaced with the name of your user-defined function. The curly braces and statements in between are called the function body.

Here is a sample program that shows how a new function is 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. We call function doPrint by appending a pair of parenthesis to the function name like such: doPrint(). Note that if you forget the parenthesis, your program may not compile (and if it does, the function will not be called).

Warning

Don’t forget to include parenthesis () after the function’s name when making a function call.

Because a function call was made, execution of statements in main is suspended, and execution jumps to the top of called function doPrint. The first (and only) line in doPrint prints In doPrint(). When doPrint terminates, execution returns back to the caller (function main) and resumes from the point where it left off. Consequently, the next statement executed in main prints Ending main().

Calling functions more than once

One useful thing about functions is that they can be called more than once. Here’s a program that demonstrates this:

This program produces the following output:

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

Since doPrint gets called twice by main, doPrint executes twice, and In doPrint() gets printed twice (once for each call).

Functions calling functions calling functions

You’ve already seen that function main can call another function (such as function doPrint in the example above). Any function can call any other function. In the following program, function main calls function doA, which calls function doB:

This program produces the following output:

Starting main()
Starting doA()
In doB()
Ending doA()
Ending main()

Nested functions are not supported

Unlike some other programming languages, in C++, functions cannot be defined inside other functions. The following program is not legal:

The proper way to write the above program is:

Quiz time

Question #1

In a function definition, what are the curly braces and statements in-between called?

Show Solution

Question #2

What does the following program print? Do not compile this program, just trace the code yourself.

Show Solution


2.2 -- Function return values
Index
1.x -- Chapter 1 summary and quiz

585 comments to 2.1 — Introduction to functions

  • 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 all code inside code tags: [code]your code here[/code]