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

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

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

  • 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 C++ code inside [code][/code] tags to use the syntax highlighter