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

  • maluba

    I just wanted to say I *love you* Alex. Seriously dude, you’re the best! I mean, I have read these things in books and all, but you just make it so easy to comprehend, I wish I started here. You really should consider converting this stuff into a book, if you haven’t already published. Wait a minute, you’re not Alex Allain (the guy who wrote Jumping into C++), are you?

    I’m really humbled by your goodwill to avail this to the world for free…

    Thank you man!

    • Alex

      I am not Alex Allain. That guy is probably way smarter than I am.

      I have gotten requests to convert this into a book, but the content is here for free, so what would be the point of that? 🙂 Okay, offline reading, I suppose. Maybe I’ll consider it someday.

      Anyway, thanks for visiting. 🙂

  • African

    Hey There, I’ve done Exercise 5

    But I really don’t understand how it works, could you please explain how this code works.

    And btw does this code violate the ‘one task’ rule of thumb for functions??

    • Alex

      Sure. Execution begins at the top of main. The user is asked to enter a number. An integer variable is defined to hold the number the user will enter. Then a number is read in from the console, and stored in the integer variable x.

      Next, we have a compound statement that calls doubleNumber(x) and prints the return value. doubleNumber() takes x and returns twice the value of x. The last lines just ensure the console pauses.

      So basically, this program asks the user to enter a number and then prints out twice that number.

      It doesn’t violate the one task rule of thumb for functions. doubleNumber() does one job (doubles a number) and main() handles the inputs and outputs. main() is simple enough that it doesn’t benefit from being broken down further.

  • joseph

    i’ve tried to compile this program many times but it’s not working
    //#include "stdafx.h" // Visual Studio users need to uncomment this line
    #include <iostream>

    int add(int x, int y)
    {
        return x + y;
    }

    int multiply(int z, int w)
    {
        return z * w;
    }

    int main()
    {
        std::cout << add(4, 5) << std::endl; // within add(), x=4, y=5, so x+y=9
        std::cout << multiply(2, 3) << std::endl; // within multiply(), z=2, w=3, so z*w=6

        // We can pass the value of expressions
        std::cout << add(1 + 2, 3 * 4) << std::endl; // within add(), x=3, y=12, so x+y=15

        // We can pass the value of variables
        int a = 5;
        std::cout << add(a, a) << std::endl; // evaluates (5 + 5)

        std::cout << add(1, multiply(2, 3)) << std::endl; // evaluates 1 + (2 * 3)
        std::cout << add(1, add(2, 3)) << std::endl; // evaluates 1 + (2 + 3)

        return 0;
    }
    my compiler keeps telling me that ‘add’ cannot be used as a function, i use code::blocks 16.1 as my compiler .

    i’m joseph

    • Paul

      Hi Joseph, I just typed your program out into Code::Blocks 16.01 on Ubuntu Mate 17.04 and it worked perfectly, I even copied the code straight from here into Code::Blocks and it also worked perfectly, so I honestly don’t know what to tell you.

      If you’re on windows then it’s possible it has something to do with MinGW, maybe try reinstalling Code::Blocks with MinGW and see if that fixes your issue.

      If you’re on a Ubuntu based distro then either try reinstalling Code::Blocks from the terminal with:

      sudo apt autoremove codeblocks
      sudo apt install codeblocks codeblocks-contrib

      or just try installing the codeblocks-contrib package by itself with:

      sudo apt install codeblocks-contrib

      (Installing the contrib package fixed a ton of minor niggles with Code::Blocks for me, it might also fix the issue for you)

    • Alex

      Works fine for me with Visual Studio 2017, and I don’t see anything amiss via inspection. What error message are you actually getting?

      • joseph

        it works fine for me with visual studio 2017 too, but it does not work with code::blocks and the error message that I get when I try to compile this program is : ‘add’ cannot be used as a function .

  • WomboCombo

    haha YES I can’t believe this man all these other youtube C++ tutorials and I couldn’t even with there basic knowledge could have done this… if you would have asked me to do exercise 4 i would have been like "Patrick *From sponge bob* saying: DUhhhhhhhhhhhh" this is how i solved Exercise 4 and 5.
    #include <iostream>

    int doubleNumber(int x)
    {
        return x * 2;
    }
    int main()
    {
        std::cout << doubleNumber(5) << std::endl;

        std::cout << "Enter a Number: ";
        int a;
        std::cin >> a;
        std::cout << "Your Number as Been Doubled: " << doubleNumber(a)  << std::endl;
        return 0;
    }
    Yes! All these other tutorials I fall off on a certain time, cause they dont explain it to well, i thought i found a guy on youtube called Chilli he was great i just fell off from not understanding. Your’s are in Explicit detail and great to follow along, even when you do the extra code to give us examples i even write them out my self to understand even more in my own way why it doesn’t work such great stuff! man thanks so much for providing this! Also i was wondering if you provided a tutorial on game programming on c++ or after this tutorial do you think(IF I completel it and IF I have a full understanding) i will be able to?

  • This is how I did exercise 5.

  • David

    Hi Alex. I found a typo for you in the quiz section.

    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, endl, namespaces, and using statements), doubles it using the doubleNumber() function you wrote for question 4, and then prints the doubled value out to the console.

    The link (1.3a -- A first look at cout, cin, endl, namespaces, and using statements) should be changed to 1.3a -- A first look at cout, cin, and endl.

  • Mandy

    i just want to say these tutorials is amazing

  • jarppa

    good tutorial 🙂

  • Virus101

    Hey Alex!

    This is how i did the program for the question 5, it is different but it worked 😛

    int doubleNumber(int x)
    {
        std::cout << "Enter an integer, i’ll double it for you :n";
        std::cin >> x;
        return 2 * x;
    }

    int main()
    {
        std::cout << "Here : " << doubleNumber(2) << std::endl;
        return 0;
    }

    Is anything done wrong here?

    • Alex

      Functionally, it works. But from a functional standpoint, it could be organized a bit better. Your doubleNumber is printing output and getting input, and doing the doubling, which is two separate jobs. It would be better to separate the output/input routines from the calculations.

    • Keno Goertz

      That is some really messy code… Your function’s parameter "x" is entirely useless which adds to the confusion. You call the function with doubleNumber(2). The 2 in there literally achieves nothing because it just gets overwritten with the user input. So if you were to do it like this, please define doubleNumber() as follows:

      However, this is still a weird way of doing it and the solution’s code is way cleaner.

  • Taksh

    Hey Alex,

    I’m a big fan of your tutorials. I wanted to ask why you told us to code using 32 bit on Visual Studio. Is there a specific reason for this? Why not on the x64 configuration?

    Thanks in advance for your time and consideration.

    • Alex

      32-bit programs tend to use less memory and are smaller, which also makes them more performant by default. 64-bit is useful if you need more than 4 GB of memory or some of the 64-bit instructions, but you probably don’t.

  • ANDY

    #include <iostream>

    //coming from python

    int askUser()
    {
        std::cout << "Please enter an Integer: " << std::endl;
        int a;
        std::cin >> a;
        return a;
    }

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

    int main()
    {

        std::cout << doubleNumber(askUser()) << std::endl;

  • Sudhanshu Kumar Ojha

    Hi alex,
    Thanks for such a good material!
    My doubt is related to quiz number 5.
    I wrote my code like this:
    #include<iostream>
    using namespace std;

    int doublenumber(int x)
    {
    return 2*x;
    }
    void main()
    {
    Cout << "enter the value to double"<< endl;
    int a;
    cin >> a;
    cout << "the result is:" << doublenumber(a) << endl;
    return 0;
    }

    I got error for above code as main should return int.
    But main function is not returning any value then why we have to make it as int main() instead of void main().

    • Alex

      Function main() always needs to return an int back to the operating system -- and your main() is returning the value 0 (via the “return 0” statement). Changing your void main() to int main() should resolve your issue.

      • Sudhanshu Kumar Ojha

        Hi alex,
        I am sorry but i am still not satisfied may be i am not clear but i have read previously that when we don’t want to return any value then we can use void.
        I have seen many examples previously when we are not returning any value hence we use void main(). The system will automatically return 0 even if we don’t return any value.
        If you are saying that main always return an integer then is it like we can never use void main()?
        I already know that changing from void main to int main will resolve the issue i already tried that 1st time itself.

        Sorry to argue on this but i am still confused.

        • Alex

          You’re conflating a couple of related things.

          For non-main functions:
          * We can use a void return type if we don’t want to return anything.
          * Functions with void return types do not return any value to the caller.
          * Functions with non-void return types must return a value.

          For main:
          * We are required to use an int return type (some compilers will let you use a void return type, but this is invalid C++ and so should be avoided).
          * If you do not return a value, C++ will return 0 on your behalf.

  • Abbas

    Hello,first thanks for your awesome website.
    then
    i just wanna know the code i wrote here(i know this is dumb question) :

    can use it in real programs this way or it takes much more time and source to do the same process ? i mean less code isn’t better?

    • Alex

      I’m not sure I understand what you’re asking. If you’re asking why we break things out into functions like this instead of putting everything into a single function, the main reason here is to start getting you used to the idea of using functions, and how to structure then. For programs any more complicated than this, functions start to become very useful for organizing your code and enabling re-use (which leads to less code).

  • My dear c++ Teacher,
    Please let me point out that in quiz, 1) and 2) questions, you speak about program fragments. American heritage dictionary first meaning for fragment is "A small part broken off or detached". My view is that they are not program fragments but complete programs though very small. Is it correct?
    By the way let me say my understanding of "argument" in c++ jargon. It is pass by value from caller function to called function parameter.
    With regards and friendship.

    • Alex

      I use the term “fragment” when I’m presenting a piece of code that can not be compiled by itself (such as a single function that isn’t main, or a few statements). In C++, an argument is the value being passed into a function by the caller. It may be passed by value, but there are other ways to pass arguments too (by address and by reference), which I cover in later chapters.

  • Akshay

    For 5th Question the input of the Variable "x" should be from User, but you didn’t do it.

    • Ram

      Yes he has.
      "std::cin >> x;" line waits for you to give the input
      Copy the codes and try to run the program, the console will wait for you to give the input.
      The program does not proceed until you give the input number

  • Good stuff. Quiz questions 1 and 2 should probably include: #include <iostream>

  • andy mackay

    Alex mate, you are a patient man, sometime I get the feeling you are doing peoples homework/actual real work for them, I would be inclined to tell folk where to go if they were asking questions that didn’t refer to the lesson at hand, what a nice guy you are.

    • ryan flores

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

      build fails everytime idk why
      Undefined symbols for architecture x86_64:
      “_main”, referenced from:
      implicit entry/start for main executable
      ld: symbol(s) not found for architecture x86_64
      clang: error: linker command failed with exit code 1 (use -v to see invocation)
      keeps saying this

  • My dear c++ Teacher,
    Please let me say I asked question at
    http://stackoverflow.com/questions/42875426/what-happens-with-one-argument-in-main
    and answer was that
    "All implementations shall allow both of the following definitions of main:
    int main() { /* … */ }
    and
    int main(int argc, char* argv[]) { /* … */ }"
    Because answerer denied explain me main()’s arguments on the ground he cannot teach me C++ like that, I ask you explain me it "like that".
    With regards and friendship.

  • Mr. Doubt

    Hi.
    For quiz 5, is it preferable to create one function to grab the number and one function to double the number or could I just let the number grabbing in the main function?
    Or, more generally, is it better to leave the main function as lean as possible, distributing most of the heavy work to extra functions?

    Edit: Guess this is answered in the next lesson.

    • Alex

      With short programs like these it doesn’t matter too much. With longer programs, I find it helpful to keep the main() function lean (just connecting a few functions together) and do all the heavy lifting inside other functions. The reasons for this are simple: other functions are potentially reusable. main() is not.

  • My dear c++ Teacher,
    Please let me send you following program as example of functions with parameters other functions. I have put function call currYear() as second parameter in function call age() for be executed first, because compilers on line execute first the second function call parameter.
    With regards and friendship.

    • Alex

      One note about this: in C++, the order that function parameters are resolved in is indeterminate. This means that in your program, birthYear() or currYear() may be evaluated first. In this program, it doesn’t matter so much, but in other programs, this might be a problem.

      Speaking personally, I find this level of nesting hard to comprehend:

      I think it’s better to use intermediate variable in this case:

      This way, the program will always execute in a deterministic manner (birthYear() called first), and we don’t have to worry about whether birthYear or currYear is evaluated first when age is called since there are no side effects involved.

      • My dear c++ Teacher,
        Please let me express my gratitude for your immediate reply. I inserted your snippet in my code and compiler
        http://cpp.sh/
        outputs:
        In function ‘int main()’:
        31:31: error: ‘birthYear’ cannot be used as a function
        32:29: error: ‘currYear’ cannot be used as a function

        My modified code is following.
        With regards and friendship.

        • Alex

          Oops, my mistake. The fact that the variable and function have the same name is confusing the compiler. Rename your birthYear and currYear variable to anything else and it should be fine. Sorry about that.

          • My dear c++ Teacher,
            Please accept my many thanks for you responded and for your helpful answer. I did it and program works fine. However your editor still sometimes does not accept "\".
            With regards and friendship.

          • Jaspal

            Hi Alex,
            Great tutorial !! I have started learning C++ few days back. Pls. advice about below program…

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

            int cyear()
            {
                int c;
                std::cout << "Enter current year: ";
                std::cin >> c;
                return c;
            }

            int byear()
            {
                int b;
                std::cout << "Enter birth year: ";
                std:: cin >> b;
                return b;
            }

            int age()
            {
                int a;
                a = cyear() - byear();
                return a;
            }

            void output()
            {
                std::cout << "Your age is : " << age() << std::endl;
            }

            int main()
            {
                output();
                return 0;
            }

            • Alex

              A few thoughts:
              1) The output() function is needless -- the std::cout line can go straight into main().
              2) age() is a calculation function which calls two input functions. That means when you call age(), you always have to enter input. Tying these two things together isn’t great. It’s better to have the program first as for the inputs, THEN do the calculation with those inputs, not have the calculation function do the asking for inputs itself (indirectly). Consequently, it would be better if main called byear() and cyear() and passed the results of those functions into age() as arguments.

              • Jaspal

                Understood 🙂
                Thanks for quick reply and nice explanation.
                Regards…

              • Hi, is my code written in a good way ? It;s giving me the expected output but I am wondering if it need any improvements?
                Thanks for any inputs on it.

  • vissa

    !bad at all 🙂
    thx a lot for the tutorials man, really helpful!!

  • My dear c++ Teacher,
    Please let me ask your help on my problem. Following program returns twice:
    Enter current year:

    Enter year of birth:

    and after I heve entered twice corresponding values outputs result.
    With regards and friendship.

    • Alex

      OutputAge() is using age() as a argument, so age() is called first. age() calls currYear() and yearOfBirth(), which ask the user for an initial set of inputs.

      The return value of age() is then passed into OutputAge(). However, because you haven’t given the function parameter a name (only a type), the parameter is ignored. OutputAge() calls age(), which prints the second set of inputs.

      If you update outputAge() like this, I think it will do what you want:

      • My dear c++ Teacher,
        Please let me express my sincere gratitude for you answered my question, moreover as you use to do. Although it looks small problem given me headache for 24 hours. I send you my code corrected according to your suggestion and also for new line. Unfortunately your editor does not accept character and also makes more problems.
        With regards and friendship.

  • Jola

    I don’t get it…
    I guess I won’t become a programmer after all…

  • Elliott

    SO I got a little help from my friend and I made the code better. Here’s what I ended up with.

  • Elliott

    I made a solution to number 5 but Im not sure it counts it does what it needs to do but I couldn’t figure out how to get the get value function to work with the doublenumber function kept getting a function cannot return 0 code so this is what I came up with, passable?

    Thanks for the tutorial just want to make sure I don't progress till I have these concepts down.

    • Kevin

      Dear Elliot;
      To get user’value, you need the "cin" not "cout" due "cout" is to print out only,
      I think your code should be like that:

  • The Q

    My code works as intended, but I’m wondering if it is wise to call a function within calling a function;

    Regards,
    The Q

    • Alex

      There’s no rule or best practice that advocates avoiding nested function calls. As long as you can do so without making your code hard to understand, then you are free to do so.

      Personally, I’d probably avoid nesting more than one level deep.

  • Therese McLeod

    Hi again, this one threw up something new: x not declared, y not declared, z not…(and then some) plus ‘add’, ‘mulitply’, etc cannot be used as a function. Am I missing a dictionary? Both compilers did the same, so I don’t know, I’m begining to dread the quizzes.
    #include <iostream>
    int add(x + y)
    {
        return x + y;
    }
    int multiply(z * w)
    {
        return z * w;
    }
    int main()
    {
        std::cout << add(4, 5) << std::endl;
        std::cout << multiply(2, 3) << std::endl;
        std::cout << add(1 + 2, 3 * 4) << std:: endl;
        int a = 5;
        std::cout << add(a, a) <<std::endl;
        std::cout << add(1, multiply(2, 3)) << std::endl;
        std::cout << add(1, add(2, 3)) <<std::endl;

        return 0;
    }
    almost forgot, they didn’t like the double brackets ‘(())’ despite all this i love learning code and I really want to keep going.
    thanks
    Therese

    • Alex

      Function parameters need to be defined like normal variables. Instead of:

      You need to do this:

  • Therese McLeod

    Hi Alex, I’ve tried this on two different compilers, using different versions of C++ and I keep getting the same response
    "error: expected ‘;’ before ‘void’ ".
    #include <iostream>
    using namespace std
    void doPrint()
    {
        std::cout << "In doPrint()" << std::endl;
    }

    void printValue(int x)
    {
        std::cout << x << std::endl;
    }
    int add(int x, int y)
    {
        return x + y;
    }
    I’ve tried different things, sometimes I get " expected ‘int’ ", and there is no ‘main()’ in this code, where do I put it?
    Thanks Therese

    • Alex

      You’re missing the ; at the end of “using namespace std;”

      • My dear c++ Teacher,
        Please let me send correct code.
        With regards and friendship.

  • Kiril

    i mean the code structure, but i see where i need to work, i need to work in my function naming. Thank you for the advice Alex!

  • Kiril

    I did it like that the input is taken in the function doubleNumber()
    program works fine but is that wrong?

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

    int doubleNumber()
    {
        int x;
        //std::cout << "Enter a number that will be multiplied by 2: " << std::endl;
        std::cin >> x;
        //std::cout << "Result is: ";
        return x * 2;

    }

    int main()
    {
        std::cout << doubleNumber() << std::endl;

        std::cin.clear();
        std::cin.ignore();
        std::cin.get();
        return 0;
    }

    • Alex

      It depends on what you mean by “wrong”. It produces the correct answer, so it’s not “wrong” in that sense. But it is wrong in that you have a function named doubleNumber() that’s not just doubling the number, it’s also asking for input. You should either name your function more accurately, or split doubleNumber() into two functions, one to do input, and one to do the doubling.

Leave a Comment

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