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 executable 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 the next few lessons, all user-defined functions will take the following form:

return-type identifier() // identifier replaced with the name of your function
// Your code here

Let’s quickly go over the 4 main elements of this:

  • In this lesson, we’ll use a return-type of int (for function main()) or void (otherwise). We’ll talk more about return types and return values in the next lesson (2.2 -- Function return values). For now, you can ignore these.
  • Just like variables have names, so do user-defined functions. The identifier is the name of your user-defined function.
  • The parenthesis after the identifier tell the compiler that we’re defining a function.
  • The curly braces and statements in between are called the function body. This is where the statements that are part of your function will go.

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

655 comments to 2.1 — Introduction to functions

  • Hello Alex, you are saying that every c++ program needs a function called "main" to be ran. But arent dlls using the name "dllmain"?

    • Alex

      I guess it depends on whether you consider DLLs to be programs or not. Maybe I should amend to say "executable program" in order to exclude library code.

  • Mal

    It would have helped me a lot if you'd explained upfront why you call functions with the prefix "int" or "void"

  • I've had the error message of "bruh": identifier not defined even tho I did and used it correctly.
    I was testing around and saw that my function is after main function compared to this which makes functions before main
    Wish there was something saying that you need to declare the function before main , but still these tutorials are the best

  • Try one out.

  • Alan Parsons

    This topic dwells on the concept of jumping out of the main function into a user-defined function and back, which does not really address the primary use or necessity of functions.

    There's nothing that can be done in a function that can't be done in main, the use is to eliminate repetitive code.  If you have a task that you will repeat multiple times in your code, and that task consists of multiple lines of code then create a function that performs the task.

    • Robert Warner

      There are a lot of good reasons to put even single use code into separate functions. It keeps your main program from getting long and confusing, you keep open the possibility of re-using the code later- even putting it in a library for other programs, other programmers on the same project can use it, you are able to encapsulate data, you can more easily change it's parameters later, it's more readable... it's just a very good idea.

    • Actually you got it exactly. It literally is about allowing you to jump from your primary code to go do something else for a moment and than come right back were you left off. That is exactly it.

      Your real question is, why is jumping from my primary code and then jumping back needed?
      The answer is to avoid re-adding the same piece of code again and again and again. Its about allowing you to have access to a small piece of functionality whenever you need it without having to re-write the same piece of code in the spot that you need it.

      So far your building simple little things but as things become more complex, the need to say, "Go do that thing you did before, again" becomes more useful. Just like we write programs to save humans from mundane tasks, the program needs functions to save programmers from mundane repetition.

      Here's a simple rule I use. If you find yourself writing the same piece of code or worse, copy pasting a piece of code to use elsewhere in the same program, it might be a good candidate for turning into a function.
      This applies to most languages too since most have subroutines or functions.

  • Arjun

    How come for some of the functions, you start them with "void" but for others you use "int"?

    • DL

      Void is the return type of the function. The keyword void is reserved and it means your function does not return anything. It just executes the statements inside of the function body.

      For example, if you want to just print something, but instead of typing std::cout << "something" all the time you want, you can simply make a void function that does it.

      void printSomething()
         std::cout << "something";

      then, on your main, you just call the function many times as you want by just printSomething().

      A function that have int as a return type, must contain the keyword return at some point of the function body, and then, alongside it, an integer value. You can, for example, create a function that executes some math, and then, return it's value.


      int getCurrentYear()
         return 2020;

      And inside of any other function, you can do, for example:

      std::cout << "Current year is: " << getCurrentYear();

      It will display

      Current year is: 2020

    • Swiss

      it's like going to the market with a bag and some money and for example your mother wants you to return with money (decimal like 2rs, 3rs but not 2.5 or 3.5) and not not to spend it all. So that means you should return with "int" after you are done with your task(Function).

      Whereas void means you are not going to return (Void) with anything.
      Similarly all other return types works the same way.

      Note: This is just an interrelation for understanding for starters, You will have a clear understanding when you practice some more. Good Luck!! (Please correct me if example could be improved.)

  • Blake

    Was doing a little practice. it compiles but does not do at all what I expected. I enter two numbers, but then they dont add and it asks for two more after that.

    • Blake

      meant to post in 2.3. didn't realize I was a few lessons behind on my PC. If I need to repost in the correct chapter I can do that.

    • nascardriver

      This discards `firstNum` and returns `secondNum`. Your compiler should have warned you about this.

      You can only return 1 object from a function. You can print "Enter two integers" in `main`, and write a function that reads in a single integer from the user. Call that function once to initialize `Num1` and once to initialize `Num2`.

    • S1lv3rW0lf2

      You could do this instead -

      This will easily output the sum of the two integers. If you want it to repeat, use a do...while loop. Of course, using it is explained in a later part of the course.

  • itsmesaz

    Hey Nascar,
    My background is mechanical, because of this pandemic i lost my job.
    Now i started learning C   in this website, It was really good for freshers to start. it was really good to understand.
    Can you suggest similar site for JAVA & SQL ?

  • itsmesaz

    Hey Nascar :)

    My profession is based on mechanical, because of this pandemic, I lost my job.
    Few days before I planned to learn C++, Java, and SQL. I got this link in GitHub. Your website is damn good. And it really very helpful for freshers to start.

    Do you have any similar platform like this for JAVA and SQL? If you have, please give me this link. I searched there are so many and it's a bit confusing to choose which one to start. I'm a beginner in this field, so guide me if you can!

    • nascardriver


      Alex is the one running learncpp. As far as I'm aware, he didn't publish any tutorials for other languages.

      If you have any questions about the lessons, feel free to ask :)

  • Nihal

    Thanks for this tutorial, because I am doing now competitive programming.This helps me so much. Thanks a lot

  • Istabi Tystab

    Hi, this code works fine but is it okay to initialize a variable with a function call or should I use a zero initialization and then a copy assignment?

  • I'm currently a technical support from a company, after my shift I go directly on this website to learn, man. In all the tutorials that I read, this is the only guide that I've become interested. I mean I tried to learn any other PL, however I think learning it is still based on the tutorial you're reading, there's a lot of tutorials in the internet but it's not like this, because I don't feel alone specially because of this comment section, it's like I'm reading this and learning this with others at the same time.

  • qwerty

    what will happen here?

  • itsArial

    I am not really sure if I should worry about the void thing when you make functions, because I don;t really yet know what it is for. If anyone can tell me I will be thankful.

  • Zach Roberts

Leave a Comment

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