Search

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’s 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 assigned the value of 6, and printValues‘s parameter y is created and assigned the value of 7.

This results in the output:

6
7

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, is of no consequence. However, if the arguments are function calls, then this can be problematic:

If the architectures 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 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:

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.

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.

Output:

9

In pictorial format:

More examples

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

This program produces the output:

9
15
10
7
6

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

Conclusion

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 and returns twice the value passed in.

Show Solution

Question #5

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

Show Solution


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

478 comments to 2.3 — Introduction to function parameters and arguments

  • Chayim

    In solution 5 in int x is used -{0}-. When is curly brackets used and when is curved used?
    How does “cin” relate to int X? Is it because it’s right after called int x ?

    • Rekt007

      int x{};  it's a type of initialization called uniform initialization,so there
      is an already defined way on how to use uniform initialization & you have to follow that.
      Generally {} are used for body,() are used while solving a mathematical expression & after a function name e.g, main()
      However if you see them somewhere else just remember them like in case of uniform initialization,you will find it easy as you progress.
      program executes sequentially ,as cin(used for taking input from console) is next statement it gonna execute right after int x{},whatever integer you types ,it gonna store it in x because you enter ">> x" (this is how cin relate to x)just after "cin"

    • To add onto what Rekt007 said, () can be used for initializations too. They don't provide the same type safety as {} does, so it's not the preferred choice.
      Some types can be initialized from lists and from individual values. When you use {}, the type will be initialized from a list. That's not always what you want, so you'd use () instead.
      You'll learn more about lists and initializations later. For now, you should always use {}.

  • Knight

    Hi, Alex could you help me answer the two questions:

    Why cannot directly use the doubleNumber(int x)  in the main function? Type name is not allowed?
    another question:

    if I used the number rather than variable. Type 4 The answer can print 8. Why?

    • You can't declare variables in an argument list. Even if you could, what value would `x` have?
      If you want to use a variable, you have to declare it before calling the function.

  • Mike

    Regarding your code:

    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. -- End Quote

    And I thought the "core of the problem here" was the fact that you initialized the num variable with a 0 rather than the obvious GetValueFromUser() as you did in the original code. I assume you did it to help transition in to using arguments and parameters.

    After further testing though, using the GetValueFromUser() as the value for 'num' doesn't work as intended. I was thinking it would pull the previous value from the variable 'input' located in the GetValueFromUser(), but obviously, that just calls the function again, which then just re asks the same question again.

    So I thought, can we replace GetValueFromUser() with the 'input' variable, since it holds the actual number. Tried, it failed because input was undefined. Why is it considered undefined, when just in the previous function, it is defined and works without issue? Aren't functions parsed in order? So if 'input' was defined prior, why is it marked as undefined in the subsequent function?

    Also, I used the code brackets to quote your code, but why are they not working? Did I use them incorrectly?

    • Alex

      > So if 'input' was defined prior, why is it marked as undefined in the subsequent function?

      Due to local scope, which is covered in the very next lesson.

      > Also, I used the code brackets to quote your code, but why are they not working? Did I use them incorrectly?

      The [code] blocks don't coexist very well with the ability to edit comments. If you refresh the page after making an edit, you should see your code highlighted properly.

  • Chayim Eliazer

    In question 2 there's another error;  -int product{ x * y };- is Unnecessary.

  • Chayim Eliazer

    Why do you keep ending all cout with '/n' when it's not necessary?

  • Chayim Eliazer

    Why use "void" even using int and not writing "return" wont return anything.

    • Ana

      Because the function isn't returning an integer, it's returning nothing, therefore the return value should be void - nothing. You could do it your way, but it's much cleaner and makes more sense to do it this way. It prevents confusion further down the line.

  • Slyde

    Hi Alex. Excellent place you have here! Please comment on my code. Is there a better way to write it? I made sure each function did just one job, then used their results in the std::cout statement.

    • Slyde

      I added another function to handle the std::cout. Is this a better practice?

    • Hi!

      Your code looks good!

      > I added another function to handle the std::cout. Is this a better practice?
      Not the way you did it. If you rename `printNumber` to `getAndPrintNumber` for example, or pass the number as an argument, then it's good.

  • Ola

    Can not compile because of "CL.exe exited with code 2."

    [code] #include <iostream>

    int getvaluefromuser()
    {
        std::cout << "Skriv et tall ";
        int X{ 0 };
        std::cin >> X;
    }

    void printdouble(int sluttverdi)
    {
        std::cout << sluttverdi << "ganger 2 er lik " << sluttverdi * 2 << std::endl;
    }

    int main()
    {
        printdouble(getvaluefromuser());

        return 0;
    } [code]

    i also tried to not use the return value as an argument but still got the same error.

    [code]
    int main()
    {
        int Num{ getvaluefromuser() };
        printdouble(Num);

        return 0;
    } [code]

  • Guy Beaubrun

    thats what i did but i did questions 4 and 5 incorrectly but doesnt the program technically functions as it should ?

    • It functions as it should, but the code isn't what it should be. Make sure you understand the solution. Function parameters are essential.

      - Enable compiler warnings, read them, fix them (Lesson 0.10, 0.11). '\n' in line 14 doesn't do anything.
      - Inconsistent formatting. Use your editor's auto-formatting feature.

  • Samira Ferdi

    Is my conclusion correct?

    return statement is the way to send out a value from function to the function caller.
    parameter is the way to send in (pass) the value to the function from outside that function.

  • Logan

    Curious, I wonder what examples would a double call like this be made for? Are there good reasons, what code like this would be used for? It is easy to see what it does but the purpose of using such a thing evades me.

    [code]

        std::cout << add(1, add(2, 3)) << '\n'; // evaluates 1 + (2 + 3)

    [\code]

  • Batman is a bitch

    Hey guys, I tried to make a complete program for question 5 of the quiz. I tried to follow the convention of using a function for specific tasks.

    So I made a function for getting user input and another function for doubling the number from the user. But I noticed that your solution to the quiz is much smaller and doesn't follow the general rule of making a function for distinct tasks.

    Would that mean my code is redundant?

    #include <iostream>

    using namespace std;

    int input()
    {
        std::cout << "Enter an integer: ";
        int input{};
        std::cin >> input;
        return input;

    }

    int doubleNumber (int x)
    {
        return 2 * x;
        }

    int main ()
    {
        std::cout <<  "Doubled number is : " << doubleNumber(input()) << '\n';
        return 0;

        }

  • yeko

    i don't know man i am new and i read your c++ basics you know (1.1 etc.) i am in the functions but i don't know why but i can't understand. i don't know man first i started your page i always say very funny page i am learning etc. but now i just look like i don't know "what is this" or "what the heck is going on?!" my sentences this now i don't know what i need to do maybe i should watch tutorials video with this you know watch tutorials read this or read this read documentation but i think videos are waste of time what i should to do alex??? i am waiting your answer

    • Joona

      You should maybe read this and previous page again. This was very difficult to me too, but just read it again and you'll understand.

      here's a very good tutorial i watch before i go to sleep: https://www.youtube.com/watch?v=_r5i5ZtUpUM&t=4s

    • Gamef

      Yeah I think you should try going to other places like solo learn, I actually finished c++ there and came here for advanced c++ tutorials, so I don't strongly recommend this for absolute beginners, it's really kind of confusing when I look at it from your perspective
      Solo learn has it's app and a website be free to choose, it's super easy and fun, plus amazing.

  • willow

    Thank you very much for the great tutorials. They are really easy to follow along.

    Found an "oldschooler" in the "More Examples" section. Line 18 should be >> int a{ 5 };

    Keep up the good work!

  • Velli

    Hello, thanks for the lessons so far. I have tried to simplify the last quiz answer as much as I could. Do you think this one would be efficient or can be simplified even more?

  • Raga

    It seems that the code snippet above :

    won't compile properly because the variable name is the same as the function name, right?

    • s1ck

      Giving global variables the same name as functions will probably result in an error.

      Giving local variables the same name as functions will probably result in an compiler warning.

      Best to avoid giving similar names.

      • Pavan

        I am also getting the same type of error. Why do we have that snippet in the tutorial then..??

        ==================================================================================

        pushb@pushb-VirtualBox:~/working_dir/learncpp(master)$ g++ -o 2_3_2 2_3_2.cpp
        2_3_2.cpp: In function ‘int num()’:
        2_3_2.cpp:5:9: error: ‘int num()’ redeclared as different kind of symbol
        int num(){
                 ^
        2_3_2.cpp:4:5: note: previous declaration ‘int num’
        int num;
             ^~~
        2_3_2.cpp: In function ‘int main()’:
        2_3_2.cpp:9:12: error: ‘num’ cannot be used as a function
          num = num();
                    ^
        pushb@pushb-VirtualBox:~/working_dir/learncpp(master)$ cat 2_3_2.cpp

        pushb@pushb-VirtualBox:~/working_dir/learncpp(master)$

  • _AC1Dfox

    First of all. Best site to learn cpp. Your doing a great job.

    This is my code for the last exercise.

    As you can see in my doubleNumber() func i declare a result var to store the result of the calculation. Is there any major difference if i only use return x * 2? (Seen on a larger scale it might be speed of the program but on a smaller scale like this it shouldn't give me any disadvantages, right?

    • * Line 5: Initialize your variables with brace initializers.
      * Missing printed trailing line feed at the end of the program.

      If you

      You'll have to

      Now you have duplicate code and a duplicate calculation. That's bad style and bad performance.

  • C++ Has Ruined my life

    Hey guys, I'm trying to explain the pass by value process in my own words to put into anki. Would you say the following description of the process is accurate?

    When a function call is made all of the parameters of the called function are created as variables, and the value of each of the arguments from the caller is copied into the matching parameters of the callee.

  • Helliarc

    I noticed and followed the original code in the examples, and when answering the quiz question, I choose different variable names for defining the user's input.  But I decided to try naming the variable 'x' across all functions and their calls, in the hopes of limiting the amount of variable names I declared, and it worked!  Is 'x' being redefined each time I declare it, staying in the same memory location?  Is this a bad practice?  I realize that we can assign the same value to multiple variables, but I feel like this is wasteful.  I can see situations where defining different variable names is desired, but for the scope of this program's intended use, maintaining the same variable name makes more sense, please correct/coach my idea, and a HUGE thank you for your series...

    • Helliarc

      The next section answers my question!  Answer to my question is: Variable 'x' is defined locally, and every function has it's own variables, which are separate and can have the same name as other variables in other functions, including main().  So although 'x' is the variable name in each function, it still has it's own memory location and they aren't related in any way.

  • Hi Alex!

    From "A warning about function argument order of evaluation" onward, you're using copy initialization.

  • Louis Cloete

    Under the heading "More examples," just below the paragraph just below the code example after "Let’s take a look at the first tricky statement in the bunch:" the second to last sentence should read: "That return value of 6 can now be used to *initialize* the y parameter of the add function."

    Also, in Quiz Question #5, int x should be initialized, even if it is assigned in the next line, as per the suggestion given earlier.

  • elFlaco

    Seems this sentence above is not formed correctly? -
    "If it is important that one argument evaluate first, you can should explicitly define the order of execution, like so:"
    (you can should?)

  • yuvi

    Hello,
    The first & second program in this tutorial cause compiler error also on the line no. 14. It should be -

    instead of -

  • abaj

    under more examples you have:

    There shouldn't be a 6 between the 9 and 15

  • Dear Teacher,
    Please let me say you that it is worthy to add in lesson that function with parameters is executed even when arguments are unused. For example:

    With regards and friendship
    Georges Theodosou

    • Alex

      It would be awfully confusing if a function call were ignored simply because a parameter wasn't used. As you've rightfully discovered, the use or non-use of parameters has no bearing on whether the function is called or not.

      Here's another interesting tidbit -- if a function parameter isn't used in the function, it actually doesn't need a name. So in the above, you could have written:

  • John

    Hi Alex, I just want to say thank you so much for these tutorials so far. I took two courses for C++ at my college but I really never understood them. You explain C++ so well and I'm actually starting to understand things rather than just memorizing them. I will keep doing these tutorials and expand on my knowledge! Thank you so much again! :D

  • Nathan

    so, I ended up doing this, and it works.  Why does using Y instead of x work? Sorry if this is an odd question

    • Alex

      The parameter name in function doubleNumber() is independent from the local variable name in function main(). You could rename "y" to whatever you want and it will still work.

      The only association between the two is that during the function call to doubleNumber(x), variable x is evaluated to get its value, and then that value is copied into the function parameter.

    • You dont even have to have the

      instead you could just type:

      and it should work!

  • Devvrat Singh

    Hi Alex! This website is in my list of my top 5 favourite websites of all time. The dedication you have (it's been a very long time)... it's just awesome! :)
    But I had a question. If I have to take input from the user, for example, I can very well do it inside a function. What, then, are parameters/arguments useful for?
    PS: Are you on any social network? I would love to know you better. :)

    • Alex

      Parameters/arguments are useful for passing data to a function that needs to perform a calculation or perform a task. For example, if you had a list of names and you wanted to sort them, writing a sort function makes a lot of sense. But where would that function get the list of names from? The answer is from the caller, passed as an argument to the function.

      • Devvrat Singh

        Thanks a lot for replying! :)
        But instead of passing values to the function, couldn't we just have called the function, and taken the input values inside the function. And, if so, isn't the need for parameters eliminated?

        • Alex

          Sure, if you wanted the user to always be the one to input values. But it's better to keep your input gathering and calculation functions separate -- that way your calculation functions can work with user input or numbers provided by the caller. If your calculation function asks for user input, then it can only be used that one way.

  • GSP

    Been loving this site so far.  Here's the code I made for this quiz.  Please let me know where I can improve so far.

    #include <iostream>

    int doubleNumber()
    {
        std::cout << "Input number to double: ";
        int x;
        std::cin >> x;
        std::cout << "Answer: ";
        return x * 2;
    }
    int main()
    {
        std::cout << doubleNumber();
        return 0;
    }

  • Ayush agarwal

    Hi Alex!
    I tried to write the program as asked in quiz 5 just the way u showed in solution but when I try to compile it , it gives me an error message C2220. "No object file generated" . Can u please tell me what is causing the problem and how to fix it

    • Alex

      This sounds like a compiler-specific issue that I probably won't be able to diagnose. I suggest using Google search and typing in your compiler's name and the error message together. Undoubtedly someone else has run into this issue and there will be suggestions you can try to fix it.

    • I ran into this same issue using VS and the default Microsoft compiler. Seems it's related to the "Treat warnings as errors" compiler flag. You probably are having some warning that is triggering the error because of that flag, so yous should either solve the warning(s) or disable the "Treat warning as errors" flag. Hope this helps!

Leave a Comment

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