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

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

  • 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! 😀

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

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