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

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

  • James Ray

    Here is my program:

    One problem that I find with my solution is that if I enter something that is not a number, e.g. a string with letters, the console returns whatever value is stored for x and double the value of x.

  • My dear c++ Teacher,
    Please let me send you my answer to exercise 5.

    With regards and friendship.

  • My dear c++ Teacher,
    Please let me report a trap in syntax. In before last line

    I omitted function name "add". All four compilers online
    1. https://www.tutorialspoint.com/compile_cpp_online.php
    2. http://cpp.sh/
    3. https://www.codechef.com/ide
    4. http://rextester.com/l/cpp_online_compiler_visual
    output 6
    and only http://cpp.sh/ throws warning:
    warning: left operand of comma operator has no effect [-Wunused-value]
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me comment, it is strange that parameters of a function are created as variables, when function is called.
    Reasonable is that be created when function is defined, for in that time type and name of parameters are declared in parenthesis, and values are assigned when function is called.
    Also numbering of lines in first example of section “How parameters and return values work together” is strange. I post program in right numbering of lines.

    With regards and friendship.

    • My dear c++ Teacher,
      Please let me report you that line numbering depends on the page size!
      With regards and friendship.

    • Alex

      Function parameters are created when the function is called for a few reasons:
      * Const parameters must be initialized when they are created -- if the variables were created ahead of time, we wouldn’t be able to initialize them with a value, since we don’t know what value they will be called with
      * Functions can call themselves (multiple times). Since the program doesn’t know how many times a function will call itself ahead of times, it wouldn’t know how many parameters to create ahead of time.

  • nopenope

  • Jay Ha

    #include "stdafx.h"
    #include "iostream"

    int Cdegree(int a)
    {
        return  (a - 32) * 5 / 9;
    }

    int main()
    {
        std::cout << "enter F degree" << std::endl;
        int x;
        std::cin >> x;
        std::cout <<"C degree is: "<< Cdegree(x) << std::endl;
        return 0;
    }

    I wrote this.
    happy

  • Made this when I was doing the Solution 4 only to realize I needed to do the whole thing in solution 5 anyhow :’D
    I guess it’s more in debth?? Dunno, just wanted to post it.

  • ramin

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

    // This function has two integer parameters, one named x, and one named y
    // The values of x and y are passed in by the caller
    void printValues(int x, int y)
    {
        std::cout << x << std::endl;
        std::cout << y << std::endl;
    }

    int main()
    {
        printValues(6, 7); // This function call has two arguments, 6 and 7

        return 0;
    }

    this code print nothing in visual c++????

  • i have tried using both return 2 * x and x + x but i keep getting a memory allocation number. my code looks like this

    • Alex

      The problem is this line:

      It should be:

      You want to call the function doubleNumber(), so you need the ().

  • Emiliano

    Check my program!

  • Jouy

    My solution:

  • Olvin Lizama

    Awesome Tutorials, here is my Answer for Quiz 4 and 5

    A bit different from your answer,

    Saludos,

  • Gustavo

  • Murlidhar

    #include "stdafx.h"
    #include <iostream>
    int getValuFromUser()
    {
        std::cout << "Enter An Integer: ";
        int x;
        std::cin >> x;
        return x;
    }
    int main()
    {
        int x = getValuFromUser();
        int y = x;
        int z = x + y;
            std::cout << x << "+" << y << "=" << z << std::endl;
        
        return 0;
    }

    Solution for Q.5. Is it a good idea? cause i dont knew how to use function (doubleNumber)
    Its working 100%.

  • confus

    I don’t get question 4. No matter what I put in it just says ”fatal error LNK1120: 1 unresolved externals”

    Even if I literally just copy paste your code it says that.

  • Khalifa

    it evaluates a value of 33 ,, my question is how can geta more accurate answer ( decimals ) ?

    • Alex

      Use a floating point type (float or double) instead of an integer type. This is covered in chapter 2.

      • Jonas

        Hi Alex. My first comment this is :p Learned sooo much only today (started c++ today), thank you very much for this amazing website!

        But I wonder (regarding the previous question) what if you don’t know what the answer is going to be?
        What if a user should input two numbers that should be divided, where 10 / 5 = 2 (a whole number), and 3 / 10 gives decimals. What on earth should we do then? Should it be int, or float?

        • Alex

          It depends on what you want. If you want integer division (drop any fractions and no worries about precision) use int. If you want floating point division (keep fractions but have to deal with precision issues) use float (or better, double). If you want to use int division for non-fractional divides and floating point for fractional divides, then you’d have figure out some way to determine which case you’re in. This seems possible in theory, but I’d have to think long and hard about how to actually do that (it would likely be non-trivial). C++ doesn’t do well when you can’t be up front about what types you want to deal with due to the strong typing rules. This is mostly a good thing, but occasionally annoying.

  • Tristan Gybels

    Can someone tell me why the console’s output is 00DC1384 instead of 5? And how to become 5 in a clean code

    • Alex

      You’re printing the address of the function rather than the return value of the function.

      Change:

      to

  • sarvesh

    thank you for C++ tutorials…very helpful for beginners like me

  • Teo

    So i put in the following code in VC and it’s not working, everything before "int doublenumber" was there (except for

    ) when i just started the project, i didn’t know what it was so i just ignored it.

    Then i get 30 errors. One saying that "doublenumber(x) must declare a body" and another one states that "not all code paths return a value" and telling me that ) was expected in unusual places, can anyone help me?
    PS: It also tells me “Alias std not found” both when using as well as not using “using namespace std;”

    • Alex

      This looks like a C# program, not a C++ program. Make sure you’ve properly installed the Visual Studio C++ compiler, and that you’re creating a C++ project, not a C# project.

  • Alex

    My code was different for the last one but I’ve got the same result, just as you said.

  • Big"B"LuvRRR

    Hey, how come

    only returns "original" value of x, 5, whereas using

    does indeed get x evaluated, with the desired value, 10, returned…???

    What’s going on , please?????

    • Alex

      Consider what happens when the top version of function doubleNumber() is called with x = 5.
      First, x * 2 is evaluated. This produces the result of 10. Because nothing is done with this evaluated value, it is discarded. Thus, x still has value 5. This function then returns 5.

      The bottom version of function doubleNumber() works as expected because after x * 2 is evaluated to value 10, that value of 10 is returned.

      You could fix the top version of function doubleNumber() by changing “x * 2” to “x = x * 2”, which is what you probably intended.

      • Big&amp;quot;B&amp;quot;LuvRRR

        Oh, wow…see, this is what’s so hard about programming for me -- while things often need to be spelled out micro-step-by-micro-step (such as "x = x * 2"), other times you can just combine things ("return x * 2")….

        Thanks a big ol’ bunch for the "think-through!"  I guess it’s a bit like learning English contractions, say -- which words can be contracted ("don’t," "can’t," etc.) and which ones probably cannot be ("tomorrow’ll be hot," "amn’t I clever" [well, this last one seems fine in "Irish English"]) -- I just gotta learn when things gotta be “spelled out” and when they can be “assumed” (“contracted”)…! 🙂

  • hi,Alex

    i don’t understand the role of void function in c++ if it returns nothing at all ?

    thank you for providing such great tutorials !!

    • Alex

      Functions can be used for lots of things besides just calculating and returning values. Imagine a function that prints a list of names to the screen. This function probably doesn’t need to return anything to the caller, so it could be declared as returning void.

  • Nyap

    So basically:

    a) Arguments are the values that are sent to the called function
    b) Parameters are the containers for the arguments
    c) Arguments can be digits, variables or function calls

    All I see scrolling down is examples which I can’t be bothered to read, have I missed anything?

  • Mohamed

    Hi , I personally didn’t understand the importance of those arguments and parameters !! isn’t easier to do this :

    instead of this :

    Can anyone please explain me in the simplest way possible why do we really need those parameters and arguments ?? Pls help me !!
    Another thing , I’m afraid I didn’t completely understand what a return sentence is !! I know this is not the right place for that but pls explain that too .
    Thanks Alex A lot for this incredible website by the way !!

    • Alex

      Hi Mohamed,

      You’re right -- it is simpler to just do the addition directly than call a function to do it. But that’s missing the point. The point of the example is to show you the _mechanics_ of how function calls and function parameters work, using examples that are simple enough that you can easily understand what they are doing.

      The return statement of the function is used to allow a function to return a single value back to the caller of the function. In the case of function sum(), the function is returning the sum of the two parameters, which is then being passed to std::cout to be printed on the console.

  • moopet

    I wonder, why I get the error message "(21): error C2065: ‘x’: undeclared identifier"
    If I repeat

    at the beginning of the main function, I still get "(25): error C4700: uninitialized local variable ‘x’ used"
    I understand, what it tells me, but I initialized x, didn’t I?
    I thought, I only had to initialize x once. However, even if

    Here is my code

    • Alex

      It’s complaining about this line in main:

      You never declared variable x in the scope of function main.

      It looks like the previous line should be:

      That way you’ll have declared x in the scope of main and initialized it with the result returned from function getValueFromUser().

  • Nyap

    Why does it still say “Process returned 0 (0x0)” when you execute your program, even when you don’t put return 0; at the end of the main function?

    • Alex

      Some compilers will assume you meant to return 0 if you forget to add a return statement to main. That’s likely what’s happening in this case.

  • pirate

    Hi Alex,
    Why cant this give the results wanted in question no. 5?

    It doesn’t double the integer input by user.

    • Alex

      Actually it does double the integer input by the user. But nothing is being done with the return value from doubleNumber(), so it is being discarded.

      You will either need to print the return value of doubleNumber (using std::cout):

      or temporarily store it in a variable and then print the variable:

  • running-song

    I’m a novice of CPP,and the following is my doubt:
    you said "return 0"meant everything went OK,but then there were many "return x*y"、"return x+y" shown up, how could I tell the difference?

    • Alex

      When I say “return 0 meant everything went OK”, I’m only talking about the return value from main (which goes back to the operating system). The return value from other functions don’t have any implicit meanings.

  • Kawasukie

    • Kawasukie

      • Kawasukie

        • Alex

          In your previous program:

          Your above program is a better solution, but for reference you could have also done:

  • J. LaDove

    Even using your code solution (Code::Blocks 13.12), I keep getting this error when I run Problem 5:

    sh: 1: Syntax error: "(" unexpected

    Process returned 2 (0x2)  execution time : 0.003 s
    Press ENTER to continue.

    ---
    inxi: 1.9.17
    Client: Shell (zsh)
    Kernel: 3.16.0-38-generic i686 (32 bit) Distro: Linux Mint 17.2 Rafaela

    • Alex

      It seems like the program is trying to run in your shell, rather than get compiled by Code::Blocks. You should check your Code::Blocks config and make sure it’s set up to compile your programs with a C++ compiler rather than run them in your default shell.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter