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:

return-type 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).


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 (here: 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
1.x -- Chapter 1 summary and quiz

617 comments to 2.1 — Introduction to functions

  • The curly braces and statements in-between in function definition are called the function body.

    The following program prints The starting main as well as the Ending main.

  • choofe

    Hi nascardriver.
    Hope you are not mad at me and my questions. I had a question about calling functions.
    I had written a code that solves a problem(irrelevant) in that code I had called a function in a 6 time loop. It runs in a time you say 5 ms. I was checking something in that function and I wrote a line that calls it once at the beginning of the code and outside of loop . when I run the code it runs faster (say 2 ms). Is there anything like caching instructions in cpu cache or something like that? or is it just coincidental (I checked about 10-12 times on each with the check line and without it and on average I got faster running with check line! Am I delusional on this? ).

    • nascardriver

      I don't follow. You removed something from your code, then it was faster. Why is this surprising to you?
      CPUs do cache instructions and data, but until I understand your question I don't think it's worth talking about low-level optimizations.

      You can use quick-bench ( )to compare function performance. Can you run your tests there and share the result (Copy url after running the benchmark)?

      • choofe

        My bad. I didn't mention that I actually added a single line that calls the function which will be called 6 more times in a loop.
        I send the code to quick-bench but I have no Idea how it works!.
        this is the address.
        I comment on the extra line

        • nascardriver

          Here's a quick-bench setup for your function. I didn't expect a difference with full optimization enabled, because all your code (minus the cout) can run at compile-time. You can play around with the optimization levels, but I don't see a notable difference. I suppose there's something off with the way you're timing your code or your compiler/cpu is applying an optimization.

  • Jim177

    Another dumb question? What is the purpose of the brackets at the end of the function, void doPrint ()?  Is it just provide a uniformity of all functions calls? I know the some parameters return data can go in there.

    Pink Warning

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

    • nascardriver

      Both are valid (Though, calling `fn2` causes undefined behavior). `fn1` is a variable, `fn2` is a function.

  • Ruben

    Here explain better than other paid courses

  • Zatch

    #include <iostream>

    void doB()
        std::cout << "Starting of DoB\n";

    void doA()
        std::cout << "Starting of DoA\n";


        std::cout << "Ending of both doA and doB\n";


    int main()
        std::cout << "Starting the main function\n";
        std::cout << "Ending the main function\n";
        return 0;

    • A. Sahni

      Hi! Well i have used the above example given in 'Calling function more than once'. Actually i am getting a  problem here that despite of using each and every code correctly.. The output does not show the do print() part that intrupts the main function. (though I am not getting any error in compilation). Program only produces main function part and does not get intrupts by do print function.
      Can u please explain why its happening? I will be very thankful to you.

  • 'Return back'

    Isn't 'Return back' the usage of redundant phrase. I think 'return' can convey the idea!

  • Precious

    This tutorial is the most precious material every c++ developer can have! Thank you so much. I wish you could publish a book out of this tutorial! It would be a best-selling.
    Thank you for all of your time, effort, energy, knowledge, experience that have been shared with us.

  • Blary

    I'm using my smartphone to do the programs ( I'm using cpp Droid as an IDE) but I'm having problems to compile this program

    [void doPrint()
        std::cout << "In doPrint()\n";

    // Definition of function main()
    int main()
        std::cout << "Starting main()\n";
        doPrint(); // doPrint() called for the first time
        doPrint(); // doPrint() called for the second time
        std::cout << "Ending main()\n";

        return 0;

    I don't see nothing wrong but the program doesn't compile
      Can anyone help me

    • nascardriver

      You're missing

      Always post error messages when you get an error.

    • Nikhil sharma

      Hello brother
      I have learnt C language but wanted to master few basic fundamentals in a more precised way and also i need to learn C++ in a best way

      So,can i consider this website as the great resources which covers everything,covering more than present on youtube(freecodecamp,mycodeschool,etc) or geeksforgeeks,tutorialspoint,etc

      Im waiting for ur reply bro

  • isn't there a way to make a function using the command "def" or something?

    • nascardriver

      Only with the preprocessor, which is bad. You need to specify the return type somewhere anyway, so you won't get closer than

      This works thanks to the trailing return type syntax

  • I did lots of programming in C++ but yet i not learn about std: i did programming in Turbo C++
    I'm confused now. before a day i read a article of internet "Learn C++ only if have mentor to guide" now i understand this line.

  • Deepak Budha

    Can you please tell me what's wrong with the below code:

    int multiply(int a, int b)
        a * b;

  • Aryan Nair

    The solution of question 2 should only have one "in doB" in the solution, as that function is only called once in the main body.

  • Vitaliy Sh.

    [details="Hi Sires!"]
    First: Can your, please, add details tag, like on


  • prince

    What do you call the variable that comes before the "main ()".
    I'm talking about the "int". And is that the only variable that we can put before the main ()? And is void is the only variable that we can use for a called function?

  • Whims

    So I think I'm missing something, on the last question, how do you end up with a second doB()??? Maybe I'm just missing something super simple but I can't figure it out for the life of me.

  • Jim

    I setup Code Blocks as shown at the beginning of these lessons. On my D: drive. Now I have questions on how to use it.

    How an I supposed to us these small program snippets?

    First off it is setup for a project. So how do I set it up to run some of the snippets shown in these lessons alone?

    I tried main menu File>New>File to run some of the snippets. But after I build and run them with C++, it just asks ne if I want to build them in a popup dialog box.

    I used CB about 6 years ago and I don't recall using it in a project mode at all.

    Note: I've been copying the snippet from these lessons and pasting them into the CB Editor/w a right click there, then us edit and paste there so I don't know it that the problem.

    I give my files D:\<name> and C++.

    How an I supposed to us these small program snippets.

  • Badreddine Boukheit

    how can I download the whole series for offline exploration please x) !

  • David Cane

    I wonder if you can upload some vedios so that I can have a more graphic understanding of these lessons even though this may be not easy.But thanks anyway.

  • hunk head

    umm excuse me but before you used "void x ( x is whatever u name the function) ()" but then in the end
    you used " int x as well" is there a specific difference betweenn the two?

  • Samira Ferdi

    does function have address like a variable?

  • Mohamed

    Thanks alot for this tutorial ,
    that's too helpful and easy to understand.

  • Liam

    I just wanted to say this tutorial is the shit, seriously. I've gone from VERY basic understanding of coding logic to feeling like I can competently learn C++ in about an hour. Thanks for taking the time to write all this!

  • Pavlo

    Hi! Thanks, for your work.

    One remark: in the first example - line 14:

    ";" is missed.

  • Hemanth Kumar


    can anybody please guide me, what is the mistake in the below program. am getting an error (am using Visual studio 2017)

    #include <iostream>

    void doPrint()
        std::cout << " In doPrint()\n";

    //definition of function main()
    int main();

        std::cout << "Starting main()\n";
        std::cout << "Ending main()\n";

        return 0;



    Severity    Code    Description    Project    File    Line    Suppression State
    Error (active)    E0169    expected a declaration    Project1    C:\Users\Hemanth Kumar VS\source\repos\Project1\Project1\Project1.cpp    12    

    Severity    Code    Description    Project    File    Line    Suppression State
    Error    C2447    '{': missing function header (old-style formal list?)    Project1    c:\users\hemanth kumar vs\source\repos\project1\project1\project1.cpp    12

  • please guide me through this and help me solve it. I am unable to understand the error displayed, according to me there's no errors in this code but there's an error popping up all the time. Please Help. I am using  

    Code Written


  • Helliarc

    Maybe it has already been mentioned, but I tried and it didn't work for me...  Are the functions built in sequence? I tried to call my second function with my first function (sequentially as declared), and function 1 failed to call function 2, but function 2 can call function 1...  I imagine the program isn't going to load ALL of the functions, but regardless of it's position of definition, shouldn't calling a function cause the program to "search" for that function that it is trying to call?

  • Oscar R.

    Ah! Now this version of is what I should of had 1 month ago! Great improvement guys

  • GG

    Alex, Relocating the DRY exercise from the chapter 1 Quiz (which was too tricky and so a bit demoralizing for newcomers) to an exercise in 2.2 section is a smart move...
    Nice to see uniform initialization being moved into chapter one, instead of creeping in after people got bad habits in the old 2.4 if i remember correctly....
    And so many other much needed improvements.....
    I was actually going to write you about all these things, glad to see everything being updated....

    in 1.10 compiler line error explanation for << being misused for cin  do not match the actually example lines  ( due to the omission of #include <iostream>), this might confuse some.

    Per our previous discussion: implementing top page navigation could be done with a simple small : < previous     next >   on the top right.

    I would also advise to change your header banner/logo on desktop as it is dated, it gives the wrong impression and might scare some away.
    Moreover, the title : and the your header: tutorials to help you master... are currently embedded as an image banner, these should be typed over your banner for SEO optimization, so search spiderscan read it and give you extra relevance.

    (while I'm at it: the ad banners background on each side being grey is feeling old or dull and does not make the ads or the center section  pop (=less ad clicks), a deeper grayish black would freshen it up but that's more of a taste thing)

    Thank you for your time.

    • Alex

      Thanks for all the feedback! The typos have been fixed. Still looking into the nav request. I'll look at the styling elements too. The site is overdue for a theme refresh but I'm not a designer so that's not my area of strength.

      • Tamir

        Hey, just want to say thanks for keeping up with all of this... this is great stuff and is really helping me out in my c++ endeavors. When I first saw some of the lessons I got worried bc some of the dates were old, but as I continued I saw updates being made so close to the current date. As a student, I just want to say I appreciate all of this and looking forward to completing the whole 'course' haha. Awesome stuff


  • Hi Alex!

    Quiz 1h says "What actually gets output depends on the compiler.".
    I don't see how this is the case. To my understanding, it's well defined.
    Function pointers can only be cast to bool, @std::basic_ostream::operator<< has an overload for bools, so that's used.

  • Kushal

    "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)."

    What will happen with 5 if it is ignored. My question is in terms of memory. When a function returns a value then where is the existence of the value even though it is gonna be ignored/deleted ? Any temporary storage area in memory ?


    • Hi Kushal!

      This is implementation defined. Most likely, the called function (In this case @return5) stores the value in memory, but the memory is overridden later without ever being read from.

      • Kushal

        Ok , thanks for the explanation :)

        One more question. I just executed last example 1h in my case it always prints 1 when I run the program.

        I replaced the rreturn5 with return10 to check but it gives error. So why does it works only for return5 ?

        Not sure why.

        • > I just executed last example 1h in my case it always prints 1
          It's supposed to do that.

          > I replaced the rreturn5 with return10 to check but it gives error
          There is nothing named "return10", so you get an error. If you add a function or variable with that name, you'll get the same output.

Leave a Comment

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