Search

1.4a — A first look at function parameters and arguments

Function parameters and arguments

In the previous lesson, you learned that a function can return a value back to the caller via the function’s return value.

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 a 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 where the value is provided by the caller of the function. Function parameters are placed 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:

Each function’s parameters are only valid within that function. So even though printValue() and add() both have a parameter named x, these parameters are considered separate and do not conflict.

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. The number of arguments must match the number of function parameters. Otherwise, the compiler will throw an error.

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 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

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.

When function add() is called, parameter x is assigned the value 4, and parameter y is assigned the value 5.

The function add() then evaluates x + y, which is the value 9, and returns this value back to function main(). This value of 9 is then sent to cout (by main()) to be printed on the screen.

Output:

9

In pictorial format:

More examples

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

This program produces the output:

9
6
15
10
7
6

The first two statements are straightforward.

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

The next pair of statements is relatively easy as well:

In this case, add() is called where x = a and y = a. Since a = 5, add(a, a) = add(5, 5), which resolves to 10.

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

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

Put less verbosely (where the => symbol is used to represent evaluation):
add(1, multiply(2, 3)) => add(1, 6) => 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 above case where one of the parameters is a call to multiply().

Before the CPU can evaluate the outer call to add(), it must evaluate the inner call to add(2, 3). add(2, 3) evaluates to 5. Now it can evaluate add(1, 5), which evaluates to the value 6. cout is passed the value 6.

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

Conclusion

Parameters are the key mechanism by which functions can be written in a reusable way, as it allows them to perform tasks without knowing the specific input values ahead of time. Those input values are passed in as arguments by the caller.

Return values allow a function to return a value back to the caller.

Quiz

1) What’s wrong with this program fragment?

2) What two things are wrong with this program fragment?

3) What value does the following program print?

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

5) Write a complete program that reads an integer from the user (using cin, discussed in lesson 1.3a -- A first look at cout, cin, and endl), doubles it using the doubleNumber() function you wrote for question 4, and then prints the doubled value out to the console.

Quiz Answers

To see these answers, select the area below with your mouse.

1) Show Solution

2) Show Solution

3) Show Solution

4) Show Solution

5) Show Solution

Note: You may come up with other (similar) solutions for #4 and #5. There are often many ways to do the same thing in C++.

1.4b -- Why functions are useful, and how to use them effectively
Index
1.4 -- A first look at functions and return values

366 comments to 1.4a — A first look at function parameters and arguments

  • Arntzen

    Why am I getting an output of "5" when I am returning both 4 and 5 (I just removed the "+" from the third code example to see what happened)?
    In my mind, I was expecting an output of "4 5".
    Why is it choosing 5 over 4? Is it just choosing the highest integer?

    #include "stdafx.h"
    #include <iostream>

    using namespace std;

    //#include "stdafx.h" // Visual Studio users need to uncomment this line
    #include <iostream>

    // add() takes two integers as parameters, and returns the result of their sum
    // The values of x and y are determined by the function that calls add()
    int add(int x, int y)
    {
        return x, y;
    }

    // main takes no parameters
    int main()
    {
        cout << add(4, 5) << endl; // Arguments 4 and 5 are passed to function add()
        return 0;
    }

    • nascardriver

      Hi Arntzen!

      Quoting from http://en.cppreference.com/w/cpp/language/operator_other
      "In a comma expression E1, E2, the expression E1 is evaluated [...] before evaluation of the expression E2 begins".

      If you enable compiler warnings you should get a warning similar to
      "warning: left operand of comma operator has no effect".

      • Arntzen

        I see, it takes the one to the right. let's say it is three parameters (a parameter is what is inside the parenthesis of a function or?). Will it then always choose the one to the furthest right?

        One more question:
        How many function types are there?
        So far we have only encountered "void" and "int" right?

        • nascardriver

          I have to step a little ahead to show examples, I'm trying to keep them as simple as possible.

          > How many function types are there?
          Infinitely many, because you can define them yourself.

          Quoting from lesson 3.4: "In almost every case, a statement written using a comma would be better written as separate statements. [...] Rule: Avoid using the comma operator, except within for loops."

          References
          * Chapter 2 - Variables and Fundamental Data Types
          * Chapter 7 - Functions
          * Lesson 3.4 - Sizeof, comma, and conditional operators
          * Lesson 5.2 - If statements

          • Arntzen

            After I wrote that comment; "how many functions types are there?", I continued on with the tutorial and found out that I acutally meant keywords. I got my answer there with the well written form 😀

            However, I am not sure what everything is called. I think the reason for this is because I took long breaks from this tutorial. I went for months.

            Therefore, can you please just make an easy code and tell me what is what so I get everything straight (I am not american and this tutorial uses some difficult words).

            In advance, thank you so much for all the help provided. I really appreciate it 😀

  • derbutzemann

    How about something like this for Quiz number 5.

  • Trevor

    Hey. Can anyone compile this for me?

    My compiler is not working so can anyone please try this and let me know if it works. Thanks for your time.

    • nascardriver

      Hi Trevor!

      You can use https://www.onlinegdb.com/ to compile/run/debug code in your web browser.

      • Trevor

        Hi nascardriver.

        Thanks for the quick and helpful reply but the link isn't working for me ):
        Can you compile this code for me? And let me know if it's working properly or not (: Thanks for responding.

        • nascardriver

          You should fix your compiler issues or search for another online compiler.

          Enter a Number you want to divide:
          9

          Enter a operand
          3

          Your Number has divided to: 3

          Enter a Number you want to subtract:
          100

          Enter a Operand:
          30
          Your Number has subtracted to: 70

          Enter a Number you want to Add:
          4

          Enter a Operand.
          5

          Your Number is Added to: 9

          Enter a Number you want to Multiply
          123

          Enter a Operand.
          3

          Your multiplied Number is: 369
          sh: 1: pause: not found

  • kartik

    for quiz 4

    • nascardriver

      Hi Kartik!

      Good job, I added some comments:

  • kartik

    I was always afraid of learning c++ cuz there is rumor around c++ is very hard but learning c++ feels very good cuz it satisfy my brain that i m learning very hard and core knowledge and with help of this tutorial
    i managed to create this silly console calculator app

    • nascardriver

      Hi Kartik!

      Your code looks pretty good for how few content has been covered so far, keep it up!

      • kartik

        what about this way

        • nascardriver

  • Zane

    I just want to thank you for everything you've done. This guide has helped me immensely so far, and answered all of my nagging questions (at least in time). I greatly appreciate the efforts you have gone to. My hats off to you, sir.

    In my spare time over the last few days, I have produced this fledgling program, utilizing the lessons thus far. It's not pretty, but I think I understand all the lessons perfectly fine. Thank you again.

    • nascardriver

      Hi Zane!

      You understood everything correctly so far, good job!

      A couple of things you should look out for in future:
      Line 4: Uniform initialization is preferred

      Line 5-7: You already named the danger with uninitialized variables. That's why you should always initialize your variables.
      Line 4-7: Global variables should be avoided. There's no way around them just yet so everything is good here. @z could be eliminated as it's only used in @XYZ.
      General:
      Inconsistent naming of variables (caps, all lower).
      Inconsistent naming of functions (lower camel case, caps, all lower).

      • Zane

        int x{ 8 }; <-- Had not learned this yet, I look forward to it.

        Lines 5-7, left it in for educational purposes. I'm trying to design the program in such a way that I could use it as a base tutorial for later reference if need be.
        Lines 4-7, I think that may be a holdover from the QBASIC experience I had as a teen. Noted.
        General:
        Working on this. Syntax in English is not lost on me, I won't let it be in C++!

        Thanks for the feedback!

        • nascardriver

          > Had not learned this yet, I look forward to it.
          Thanks for pointing it out, I though it was covered in the first lesson about initializations. It's in 2.1

          • Zane

            So this throws 9 errors, mostly for undeclared identifiers. I know that they should be initialized during declaration. I am working on that. I've a question first, though... if declaration/initialization of the variables should be done within the body of main(), or at least not as global variables, how does one declare them without the compiler bitching so much? I have to reference some of them in my function initializations, so how do I do that without pissing off the compiler?

            Edit (follow-up thought): Should it be that I make much heavier use of local variables within functions, and pass those values around instead?

            • nascardriver

              > if declaration/initialization of the variables should be done within the body of main()
              You should initialize variables where they're declared (There'll be exceptions to this in the future). No matter if they're inside @main or somewhere else.

              If you need global variables you declare them globally. You can't declare a variable in @main and use it in @XYZ, @XYZ doesn't know about anything in main.

              > Should it be that I make much heavier use of local variables within functions, and pass those values around instead?
              Yes

              Your code without errors:

  • Wo0d Glue

    Hello Alex
    I'm having some problems creating a lot of the code in this chapter and I'm not sure if its me doing something wrong or if it's Visual Studio.
    After a lot of frustration I decided to just copy the solution to the last question but it isnt working.

    'cout': is not a member of 'std'
    'cout': undeclared identifier
    'endl': is not a member of 'std'
    'endl': undeclared identifier
    'cin': is not a member of 'std'
    'cin': undeclared identifier

  • Legion

    Regarding Quiz Question number 5,
    I first tried to attempt the question without checking the solution and while compiling it, the program ran into an error,
    here's my code:

    When I was typing this program for the first time I didn't initialize 'epsilon' under 'main()' function  believing that it should work out since its already initialized in my 'twice()' function, naturally I got the error- 'epsilon': undeclared identifier (in the 14th and 17th line), then I initialized it under the 'main()' function also (as you can see in the above typed code) and yet again I ran into an error, eventually I had to check out the solution but what is wrong in this code and if there's a way to rectify it then how can it be done?

    • nascardriver

      Hi Legion!
      The epsilon in your twice functions has nothing to do with the epsilon in main.
      You could rename one without affecting the other.
      The problem is that you didn't initialize your variables epsilon and gamma in main (line 13) but you're trying to access to value of epsilon in line 14.
      Whenever you create a variable you should initialize it with a default value.

      This isn't the solution to the quiz yet. Try finding the it without looking at the sample provided by Alex.
      If you need any more help feel free to ask.

      • Legion

        Thanks for the reply!

        Although, in the code which you gave me - how is the compiler getting to know that the value taken from the user in the form of the gamma variable is equal to epsilon?
        Also, omit '#include<conio.h>' (We use turbo c++ compilers at school, and I'm just used to typing it everywhere :p)

        • nascardriver

          (1)
          It doesn't. In line 11 (my example) variables epsilon and gamma get created. In line 19 the user inputs a value which is stored in gamma. epsilon is still 0.
          Line 15 wouldn't change anything.

          (2)
          Caused by (1)

          If you want me to tell you why it isn't working just say it. But I think solving this on your own will help you understanding the language.

  • Legion

    Hey Alex! I tried to make an alphabet printing version of the given example  

    Here's the one which I made and I ran into a problem 🙁

    Can you tell me how to rectify this error? 🙂

    • nascardriver

      Hi Legion!
      When you write a or b in your source code the compiler will search for variables/constants/functions named a or b. But you have no such variables/constants/functions so your compiler complains.
      What you need to do is surround the characters with ' these things.

      • Legion

        Thanks for the fast reply 😀 , I googled why I shouldn't use "using namespace.std;"

        P.S - There's a small typo in line 7 and 8 where "std::" has been repeated twice.

        • nascardriver

          Thanks for pointing out the typo, I cannot edit my post anymore though.

          In a small case like yours it isn't particularly dangerous. However, when you get to larger projects you'll find yourself using functions from from several different namespaces where some namespaces might have functions with the same signature (return type, parameter types).
          If that's the case and you're 'using' two namespaces which contain functions with equivalent signatures you won't be able to tell which one you're actually calling.
          You could continue 'using namespace std' for now, but this will just turn into a bad habit which you'll have to get rid of sooner or later so you might just as well not get used to it at all.

  • Santa

    Hi~ Alex Happy new year!
    I have a question..
    And here is my code

    #include  "stdafx.h"
    #include <iostream>

    int cin()
    {
        std::cout << "정수를 입력하세요";
        int x;
        std::cin >> x;
        return x;
    }

    int doubleNumber(int x, int y, int z)
    {

        std::cout << "x * y / z = ";
        return x * y / z;
    }

    int main()
    {
        std::cout << doubleNumber(cin(), cin(), cin()) << std::endl;
        return 0;
    }

    I don't know why this does not work..
    and when I change the location of two argument which "int x" and "int z"
    It works.. I'll be waiting for your answer

    • Alex

      It doesn't work because your system is resolving the doubleNumber() parameters from right to left instead of left to right like you might expect (the C++ specification doesn't specify which way function parameters evaluate, so the system can do whatever is most performant).

      You should always call functions in such a way that the order of evaluation of the parameters doesn't matter. In this case, that can be accomplished like this:

      Because the initialization of x, y, and z now happen in separate statements, they have a deterministic ordering. And then when we get to doubleNumber, it doesn't matter whether the parameters are evaluated left to right or right to left.

  • Muffin

    Hi! Alex, why do we have to write "std::" everywhere? I mean it works just fine without it ( "cin" instead of "std::cin" ect.) Is it just "good manners" like writing "return 0" in the end of the main function or does it have some practical use? Thanks in advance! 😀

    • Alex

      1) Using the std:: prefix helps prevents naming conflicts. It also helps make clear to the caller which functions are user-defined vs from the standard library.
      2) It doesn't work fine without it unless you use "using statements", which can cause naming conflicts.
      3) If it works fine without it, you're either using an outdated compiler, or you're including the .h headers rather than the headers without extensions.

    • wendigo

      you can write using namespace std before you write a function

  • Name

    I can`t really understand what I am learning at this point. Do you know why could it be so?

  • Thirteen Spades

    I'm on Visual Studio, and for some reason when I make a solution, close out that project, and then open another one, I have to close out Visual Studio and re-open it to use a different solution.  Why?

  • Dan the African

    Alex i was looking through Forums the other day and many people suggested i learn C# the C++, so should i Stop learning C++ and start C# and after C# learn C++ or should i continue learning C++, Help PLease!!

    • dolx

      I've heard C# is more practical for a beginner to learn OOP programming due to the complexity of C++. If the tutorials here are very difficult to grasp then perhaps you can go to an easier tutorial (Such as Bucky's tutorials) or go to C#. I've been doing this for a few months with no real issue other than sometimes being confused so I'm going to continue. Sorry for the late reply too, I just started on this website (Although, as aforementioned, I've been doing this for a few months so I don't know how hard these tutorials are for a complete beginner. I'm just here to get a better grasp of the language).

  • TheJAGUAR

  • JJ

  • Liam

    First time learner here.

    To declare variable, you give "int x", whereas to declare a function you give "int x()". Does the compiler see the comma and work out that it must be a function, or are a variable and a function the same on some esoteric level?

    • Alex

      I don't see a comma there. The compiler is able to differentiate between a variable and function declaration because the function declaration has a parameter list (the part between parenthesis, which may be empty).

      • Liam

        Haha, you're right--the question didn't make any sense at all (any anyway, you answered it in one of the next chapters).

        If I had included a header " #define comma bracket ", the question would have compiled correctly 😀

  • a human

    how to make these all outputs in one line in the console window ?

Leave a Comment

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