2.3 — Introduction to function parameters and arguments

In the previous lesson, we learned that we could have a function return a value back to the function’s caller. We used that to create a modular getValueFromUser function that we used in this program:

However, what if we wanted to put the output line into its own function as well? You might try something like this:

This won’t compile, because function printDouble doesn’t know what identifier num is. You might try defining num as a variable inside function printDouble():

While this addresses the compiler error and makes the program compile-able, the program still doesn’t work correctly (it always prints “0 doubled is: 0”). The core of the problem here is that function printDouble doesn’t have a way to access the value the user entered.

We need some way to pass the value of variable num to function printDouble so that printDouble can use that value in the function body.

Function parameters and arguments

In many cases, it is useful to be able to pass information to a function being called, so that the function has data to work with. For example, if we wanted to write a function to add two numbers, we need some way to tell the function which two numbers to add when we call it. Otherwise, how would the function know what to add? We do that via function parameters and arguments.

A function parameter is a variable used in a function. Function parameters work almost identically to variables defined inside the function, but with one difference: they are always initialized with a value provided by the caller of the function.

Function parameters are defined in the function declaration by placing them in between the parenthesis after the function identifier, with multiple parameters being separated by commas.

Here are some examples of functions with different numbers of parameters:

An argument is a value that is passed from the caller to the function when a function call is made:

Note that multiple arguments are also separated by commas.

How parameters and arguments work together

When a function is called, all of the parameters of the function are created as variables, and the value of each of the arguments is copied into the matching parameter. This process is called pass by value.

For example:

When function printValues is called with arguments 6 and 7, printValues‘s parameter x is created and initialized with the value of 6, and printValues‘s parameter y is created and initialized with the value of 7.

This results in the output:


Note that the number of arguments must generally match the number of function parameters, or the compiler will throw an error. The argument passed to a function can be any valid expression (as the argument is essentially just an initializer for the parameter, and initializers can be any valid expression).

Fixing our challenge program

We now have the tool we need to fix the program we presented at the top of the lesson:

In this program, variable num is first initialized with the value entered by the user. Then, function printDouble is called, and the value of argument num is copied into the value parameter of function printDouble. Function printDouble then uses the value of parameter value.

Using return values as arguments

In the above problem, we can see that variable num is only used once, to transport the return value of function getValueFromUser to the argument of the call to function printDouble.

We can simplify the above example slightly as follows:

Now, we’re using the return value of function getValueFromUser directly as an argument to function printDouble!

Although this program is more concise (and makes it clear that the value read by the user will be used for nothing else), you may also find this “compact syntax” a bit hard to read. If you’re more comfortable sticking with the version that uses the variable instead, that’s fine.

A warning about function argument order of evaluation

The C++ specification does not define whether arguments are matched with parameters in left to right order or right to left order. When copying values, order is of no consequence. However, if the arguments are function calls, then this can be problematic:

If the architecture evaluates left to right, a() will be called before b(). If the architecture evaluates right to left, b() will be called before a(). This may or may not be of consequence, depending on what a() and b() do.

If it is important that one argument evaluate first, you should explicitly define the order of execution, like so:


The C++ specification does not define whether function calls evaluate arguments left to right or right to left. Take care not to make function calls where argument order matters.

How parameters and return values work together

By using both parameters and a return value, we can create functions that take data as input, do some calculation with it, and return the value to the caller.

Here is an example of a very simple function that adds two numbers together and returns the result to the caller:

Execution starts at the top of main. When add(4, 5) is evaluated, function add is called, with parameter x being initialized with value 4, and parameter y being initialized with value 5.

The return statement in function add evaluates x + y to produce the value 9, which is then returned back to main. This value of 9 is then sent to std::cout to be printed on the console.



In pictorial format:

More examples

Let’s take a look at some more function calls:

This program produces the output:


The first statement is straightforward.

In the second statement, the arguments are expressions that get evaluated before being passed. In this case, 1 + 2 evaluates to 3, so 3 is copied to parameter x. 3 * 4 evaluates to 12, so 12 is copied to parameter y. add(3, 12) resolves to 15.

The next pair of statements is relatively easy as well:

In this case, add() is called where the value of a is copied into both parameters x and y. Since a has value 5, add(a, a) = add(5, 5), which resolves to value 10.

Let’s take a look at the first tricky statement in the bunch:

When the function add is executed, the program needs to determine what the values for parameters x and y are. x is simple since we just passed it the integer 1. To get a value for parameter y, it needs to evaluate multiply(2, 3) first. The program calls multiply and initializes z = 2 and w = 3, so multiply(2, 3) returns the integer value 6. That return value of 6 can now be used to initialize the y parameter of the add function. add(1, 6) returns the integer 7, which is then passed to std::cout for printing.

Put less verbosely:
add(1, multiply(2, 3)) evaluates to add(1, 6) evaluates to 7

The following statement looks tricky because one of the parameters given to add is another call to add.

But this case works exactly the same as the prior case. add(2, 3) resolves first, resulting in the return value of 5. Now it can resolve add(1, 5), which evaluates to the value 6, which is passed to std::cout for printing.

Less verbosely:
add(1, add(2, 3)) evaluates to add(1, 5) => evaluates to 6


Function parameters and return values are the key mechanisms by which functions can be written in a reusable way, as it allows us to write functions that can perform tasks and return retrieved or calculated results back to the caller without knowing what the specific inputs or outputs are ahead of time.

Quiz time

Question #1

What’s wrong with this program fragment?

Show Solution

Question #2

What two things are wrong with this program fragment?

Show Solution

Question #3

What value does the following program print?

Show Solution

Question #4

Write a function called doubleNumber() that takes one integer parameter. The function should return double the value of the parameter.

Show Solution

Question #5

5) Write a complete program that reads an integer from the user, doubles it using the doubleNumber() function you wrote in the previous quiz, and then prints the doubled value out to the console.

Show Solution

2.4 -- Introduction to local scope
2.2 -- Function return values

521 comments to 2.3 — Introduction to function parameters and arguments

  • David

    This is what I came up with:

  • Marius

    As an amendment to the first problem of the printdouble() not having a value I came up with this. Are there other reasons than the educational one (transition to the lesson) that you didn't show this? It seems most straightforward.

    Thank you for your ressources, free and well-made at the same time!

    • nascardriver

      Your call to `getValueFromUser` in `main` doesn't do anything useful, it should be removed.
      As the name suggests, `printDouble` is supposed to print a doubled number, _not_ read it. By moving the call to `getValueFromUser` into `printDouble`, `printDouble` can no longer be used to print anything else.

  • Ali

    Why does it give me the error :
    Error (active)    E0020    identifier "valueTyped" is undefined

    • nascardriver

      `valueTyped` doesn't exist in `Double`. Functions cannot see variables declared in other functions. You need to store the return value of `getValueFromUser` in a variable in `Double` (See previous lesson).
      You're also never calling `Double`. C++ is case-sensitive.

  • Your neighbour at 3:00 AM

    Hello Nascardriver/Alex!
    These are really amazing tutorials.

    I wrote this code to check the order of evaluation of function arguments-

    I checked it in both codeblocks and tutorialspoint compiler.
    It gives output-

    So why does the compiler choose to evaluate function arguments from right to left(and not left to right like a normal person would do it)???


    • nascardriver

      You'll need to know stacks to understand my answer. We explain stacks later in the lessons. Basically, you can think of the stack as a stack of plates in your kitchen. When you _push_ something onto the stack, you put a plate on top. When you _pop_ something, you take the top plate off. You can only take the top plate, all other plates are blocked.
      x86 assembly (The language your CPU speaks) uses a calling convention in which the arguments get pushed onto the stack in reverse. That way, when the called function pops the arguments off of the stack, it gets the first argument first, the second second, and so on.

  • Eit

    The compiler seems to not allow function calls if the current function is calling another function that is below it, it seems to think the function is undefined, is this normal behavior in C++? I know this was the case in older versions of C but not in modern versions.

  • akaNegrU

    So, i came up with this:

    The question is: How do i get the value of input without the double / 2 trick?

    LE: oups, already figured it out:

    • nascardriver

      > already figured it out
      That doesn't work. It will prompt the user twice. You'll want to add a second parameter to `printDouble`

      • akaNegrU

        So just to be clear i'll paste the modified code again:

        It works for me, hopefully not by mistake :D

        • nascardriver

          No, you'll be prompted twice, eg.

          • akaNegrU

            I'm not lying! :) It only ask me to input once.

            • nascardriver

              The file you edited is "function call double.cpp", but you're compiling "ConsoleApplicationTemplateZero.cpp".
              "function call double.cpp" doesn't show up in your "Source Files" on the right hand side, you created it in a wrong directory. VS has weird directories. I don't have VS, so I can't tell you how you did it wrong. Look up somewhere how to add source files to a project in VS.

              • akaNegrU

                Yes, it might be that. Because all of the project settings i have to modify as i create every new one, i made a template i load every new project and save it with another name. I'm aware that this is not the way, but if this is why my code is working so be it.
                PS: but i don't think so... Anywayz, thanks for replys!

  • akaNegrU

    "Question #4

    Write a function called doubleNumber() that takes one integer parameter and returns twice the value passed in."

    As a non native english speaker i didn't understand the question. What i read is .... "returns twice" as in (use the return statement twice). And i already know that the 1st return statement will be passed then the function stops, so it was confusing.
    Maybe the word 'double' instead of 'twice' would be a better choice, as in so many examples before.
    And again excuse my english and thanks!
    LE: Looking for the expersion "twice the value" ( ) it's now obvious for me, what you meant, and in any other context this expression would not have give me such a hard time. At the time of reading thou, 'twice' for me only meant 'two times'  as in 'returns two times', that's why i think the word double/doubled is beter.

  • Jason Myres

    Firstly, I'm hoping I did the code input correctly to have it show below in coding format :)
    And if not, I'll learn, I guess. Anyway, my code below, how can it be improved using past lessons? So, from 2.3 < 1.1 (I believe).

    I've been learning for roughly 2 weeks now (9 days). Missed 3 due to laziness. Even if it's not the best code, I'm still happy with it.
    I have a very hard time learning from text, and since this entire site is built off of text, you can guess I struggle.
    I often spend over 40+ minutes on a single lesson when I try learning for 1 hour a day. So, pretty problematic.

    • nascardriver

      It's good practice to print a line feed (\n) at the very end. Otherwise another program might print on the same line as yours, which looks bad.
      `using namespace` can lead to name collisions and should be avoided.
      You might need a little longer, but this isn't a competition, take your time :)

  • Robbas

    Hello, I would a clarification about this warning:

    "The C++ specification does not define whether function calls evaluate arguments left to right or right to left. Take care not to make function calls where argument order matters."

    In this lesson we used addition and multiplication so the order it doesn't matter how you said.
    But for example if I wanted to use subtraction or division I would have to follow the following rule, is it correct?

  • osber

    So, I started this tutorial 3 days ago, and I made this.
    I know it can be vastly improved, but oh man I'm happy.

    There are no words to thank you for this. I'm so happy! I can't wait to learn more and improve the little thing I made!

    Ignore the welcome and goodbye functions, those were my function call practice lol

  • Vitaliy Sh.

    Hi Sires!

    Also, can your please change 4 "before std:cin" { 0 }s to { }; here?

  • How about using multiple functions? Is this correct or not? Thank you for your work!

  • prince

    In our fixing our challenge program
    why does the int value parameter gets it's value from the getValueFromUser funtion?
    and why does the int value named like that? both int and value is a reserve keyword right?

    and can you please explain the use of the int value parameter that you used?

    • nascardriver

      The return value of `getValueFromUser` is stored in `num` (Line 19). `num` is then passed to `printDouble` (Line 21).
      "value" is not a reserved identifier, the syntax highlighting on learncpp makes it seem like it is, but it isn't.
      We use a parameter because we want to transport a value from one function to another.

  • Kermit

    so far

  • abdul khaleqh

    • nascardriver

      - Don't use "using namespace".
      - Don't use `std::endl` unless you need to.
      - Initialize variables with brace initialization.
      - If your program prints anything, the last thing it prints should be a line feed ('\n').

  • Centriax

    When should you be using "int" and when should you be using "void" and how do they differentiate from each other?

Leave a Comment

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