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:

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

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

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

  • Yahsharahla

    Hi I decided to post mine since it looks like I chose a different way to make this program but with the same results.

  • Lakshya

    here is my code :

  • WordPress

    Alex, are parameters only used for mathematics?
    By the way, I found out a way to calculate the addition of two numbers with only one function =D

    #include(less than)iostream(more than)
    #include(less than)conio.h(more than)
    using namespace std;
    int main(){//returns 0
    double dA,dB,dC;
    cout<>dA;
    cout<>dB;
    dC=dA+dB;
    cout<<dA<<" + "<<dB<<" = "<<dC<>dA;
    cin>>dB;
    dC=dA+dB;
    cout<<dC;
    }

    • WordPress

      ?? My code’s gone haywire… Let me retype it here:

      int main()
      {
      double dA,dB,dC;
      cin>>dA;
      cin>>dB;
      dC=dA+dB;
      cout<<dC;
      system("pAuSe";
      }

    • Alex

      Parameters can be used for all kinds of purposes. Mathematics just makes for easy examples because (almost) everyone intuitively understands how to add and subtract small numbers.

  • ingthinks

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

    int doubleNumber(int x) // doubles value of x
    {
    return x * 2;
    }

    int main()
    {
    using namespace std;
    int x; // declares variable x
    cout << "Input an integer to double: ";
    cin >> x; // defines x as users input
    cout << x << " doubled is " << doubleNumber(x) << endl;
    return 0;
    }

  • ingthinks

    Here is my solution to #5:

    #include “stdafx.h”
    #include

    int doubleNumber(int x) // doubles value of x
    {
    return x * 2;
    }

    int main()
    {
    using namespace std;
    int y; // declares variable y
    int x; // declares variable x
    cout <> x; // defines x as users input
    y = x; // defines y as equal to x to display the number that was doubled
    cout << y << " doubled is " << doubleNumber(x) << endl;
    return 0;
    }

    • You don’t actually need y, as you can simply do this
      cout << x << " doubled is " << doubleNumber(x) << When you take the x the first time, it will hold the original number, when you use doubleNumber, it will output the result of x * 2.
      That way the code is more optimized, as it requires less memory to hold the values, and it will no longer need to assign the value of x to y, which is a waste of CPU cycles (I know that in this case the difference will be a nanosecond at most, however in bigger programs this difference might be seconds).

      • ingthinks

        i see, thanks for helping me to understand this better
        here is my updated code:

        #include “stdafx.h”
        #include

        int doubleNumber(int x) // doubles value of x
        {
        return x * 2;
        }

        int main()
        {
        using namespace std;
        int x; // declares variable x
        cout <> x; // defines x as users input
        cout << x << " doubled is " << doubleNumber(x) << endl;
        return 0;
        }

        same functionality as my original program but i can see how this is a better way of doing it

  • cooper507

    in the piece of code, for example:

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

    does it matter that when you create a function you have the (int x, int y) in the parenthesis? what does it do for the function?

    heres another example:

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

    • Alex

      (int x, int y) are the function parameters. Without them, the compiler won’t know what x and y are inside of the add() function, and you won’t be able to pass values into add().

  • Hey, I’m new to C++, and I answered question 5 as follows:

    It works, but is not included in the answers…so, is it a correct way?

    • Alex

      If you define “correct” as producing the right answer, then it looks correct. There are usually many ways to do the same thing in C++. Sometimes one way is better than another, but other times, it’s just a matter of preference.

      You could improve this program by getting rid of line 12 (int y=2) and changing the last line to:

  • Bryan

    Here is what I came up with for question 5

  • me

    finally! addition of 2 numbers

  • DarkOwner94

    Hey nIce tutorial i am understanding it 🙂
    btw here is my code for solution 5 -.^

  • Lenny

    I love my solution for question 5:

    Nice Tutorial so far!

  • AlkieP

    On solution 5 you have two solutions to do the same thing:

    This,

    and this:

    I understand that this is a small simple program where performance isn’t an issue, but if hypothetically this was a program with a much larger scale, is there a difference in speed/performance between these two techniques? The first one seems shorter, and therefore faster?

    • Alex

      The program with x = doubleNumber(x) has an extra assignment operation that happens, so it would be slightly slower.

      The speed difference would likely be unnoticible unless you were running this thousands of times.

  • Leo

    These tutorials are incredibly well constructed and very easy to understand. Many thanks to the author! I also love the quizzes! Here’s what I came up with for #5:

  • Marco

    hey i have a problem with the following code:

    it gives me this error:
    In function “int main()
    “multiply” undeclared (first use this function)

    I don’t understand what went wrong

    • Howard

      Marco, you misspelled multiply when you wrote the function. But you spelled it correctly when you called it from main. So the compiler was expecting a function called multiply, which doesn’t exist in your program, although one called multipliy does. To fix the error, either change the function name to the correct spelling, or misspell it the same way in the function call. I’d go for my first suggestion, though either will work.

    • Gizmo

      Hello, Marco its just a typo. You misspelled multiply

  • Jil

    when we write a program like this, it will not work

    #include “stdafx.h”

    #include “iostream”

    int main()
    {
    using namespace std;
    int numb,a;
    cout << "Enter number" <> numb;
    a = doubleNumber(numb);
    cout << a;
    return 0;
    }

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

    • Jil,

      In the third line,

      should be

      .
      Also, int main() should be at the bottom of the program. (or write

      under the
      #include .

      I hope that helps.

  • Dino

    First of all kudos for the great site you have.
    I had a little problem with exercise 5. My solution was this:

    The problem is that the value is not doubling. Doing a debug, I saw that the function was called correctly, x was calculated as it should inside the function, but never returned to main. Doing a x=myFunction(x) resolves it, but I don’t understand why? If I’m simply using a myFunction(x) isn’t x supposed to get the new value calculated inside the function?

    • madryoch

      Try using x=doubleNumber(x); instead of doubleNumber(x);

      or

      Remove doubleNumber(x); and correct the following to:

      cout << "The result is " << doubleNumber(x);

      The reason this happens would be if i am not mistaken that x variable in doubleNumber function is active only while in the function itself so when the control returns to main the x in main being a different variable has the set value of what u ve inserted with cin.
      Note that the returned value of ur doubleNumber function is not saved anywhere thus is not accessible…

      So the solution is either assign the returned value to x in main function or ask from cout to execute the doubleNumber function and print the returned value right away…

      Hope i helped… 🙂

      • Big"B"LuvRRR

        But the x in doubleNumber() is **returned** to main() so I don’t understand how what you say explains the issue.

        Why does

        work but

        doesn’t???

        • Big"B"LuvRRR

          Uh, never mind -- Alex’s explained it below: the x is indeed returned in the second situation but its value is the same one that was originally passed into the function because the computer must be told (via a statement like "x = x * 2;") that x will now have a new value!

  • Anon

    Why doesn’t this work?

    • rose

      you used two parameters in doubleNumber function definition, but during function call only one parameter..number of parameters must be same.
      and also doubleNumber must return a value.

      • Alex

        Correct. The last line of main should be:

        Because you’ve defined your function to take two parameters, and if you want to double z, you need to pass in 2 as the second parameter.

        That said, it’s weird to call your function doubleNumber when it actually multiplies two numbers (one of which may or may not be 2).

    • 1DoRa

      There are 2 problems in the code.

      1) You did not return anything in doubleNumber fucntion
      2) last line in the main() function, you did not pass the values properly

      Here is the correction

      • Chinmaya

  • GlassJoe

    Thanks Alex!
    I compiled my first little program for Quiz Question 5 and it was great: worked like a charm and basically matched your solutions!
    But then I showed it off to my girlfriend… She entered an unfathomable positive number in the console (to be doubled), but the result came back negative.
    What’s going on to cause this? When I use integers of a smaller magnitude everything seems to work perfectly.

    Just curious. -Joe

    • Ron

      I may be wrong on this, but I think this is because of “rollover.” in other words, there is a maximum value that can be stored as an integer, and as I read somewhere else, when you perform an operation on a positive integer that makes it larger than the max, it rolls the number over to the smallest number (kinda like an odometer). In the case of integers, its a negative number.
      I first learned MATLAB programming, and when you went overboard there, it just returned “inf” for infinity. At least with that I could understand what had happened lol.

    • madryoch

      Hmm i hope this helps. When you type int variableName; it creates a reference in RAM for variableName and occupies a specific number of bytes for int types.Either you initialize the variable or not, the number of bytes occupied by the variable are specific for ALL variables of a specific type.Now There are types of int … e.g. unsigned short int and signed short int both take same bytes in RAM which means they can hold up to a specific maximum of different numbers.
      Unsigned short int range = numbers from -32768 to 32767. Total numbers stored = 32767-(-32768)= 65536 numbers
      Signed short int range = numbers from 0 to 65535. Total numbers stored = 65535 plus one which would be the number zero = 65536 numbers total…

      So when u type int the compiler automatically sets it to signed int…
      What happens then when u make mathematical equations that exceed the limits ?
      The extra digits of the calculations are overflowing so they never get saved… which results in the following for signed short int…

      Let’s say we have a result of 32768…= 32767+1 so it restarts at -32768.
      Further Explanation with binary system…

      number 15 = 1×8 1×4 1×2 1×1 = 1111 in binary digits
      number 16 = 1×16 0x8 0x4 0x2 0x1 =10000 in binary digits

      Imagine now that u can only keep 4 binary digits(ammount of memmory space a variable of specific type takes) …
      So 10000 that has 5 digits looses the first digit and is saved as 0000. Number 0 in decimal
      4 binary digits means numbers from 0 to 15 (16 total numbers) That way if u try to store a larger number the counter will start anew as explained above…

      Sorry if my explanation is not very good . English is not my native language but i really hope u understand how it goes…

  • Teclo

    I’m confused by this:

    int add(int x, int y, int z)
    {
        return x + y + z;
    }
    
    int multiply(int x, int y)
    {
        return x * y;
    }
    
    int main()
    
    {
        cout << multiply(add(1, 2, 3), 4) << endl;
        return 0;
    }

    Can you explain how x, y and z are being attributed there. I thought you had to say x = 7 or whatever, but here there’s nothing like that. Is it down to the order you write x, y and z in along with the order of the numbers later on? Or will it just attribute the values to x first, then y, then z, no matter what order you wrote them in (e.g. z, x, y)?

    • csvan

      When you call the function add(int x, int y, int z), the compiler is expecting 3 integer values within the parentheses, in that exact order, separated by commas. The integer values that are passed this way are in turn assigned to x, y, and z.

      Thus, when you write this call: add(1,2,3), it is equivalent to add(x = 1, y = 2, z = 3), and the functions will treat these variables (x y and z) as having those values, as long as the function is running.

      In other words, by calling add(1,2,3), you are really giving values to the variables in question, just as it should be.

      It helps if you try to think of functions as separate from each other, just like Alex explained: A function returns a value to the caller, and the caller can pass parameters to the function being called. What this means effectively is that x, y and z are variables LOCAL to the function add (not main()!), and main simply helps the function add by telling it what value it should give to its variables.

      Hope that helps! Send a mail otherwise (csvanefalk@hushmail.me). Of course, you should also ask Alex, I don’t know how often I will be checking these comments!

  • Steve

    hi alex.

    I’m doing question 4 and it doesn’t seem to work. i have

    This is my error:

    1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
    1>C:\VC2008 PROJECTS\HelloWorld\Debug\HelloWorld.exe : fatal error LNK1120: 1 unresolved externals
    1>Build log was saved at “file://c:\VC2008 PROJECTS\HelloWorld\HelloWorld\Debug\BuildLog.htm”
    1>HelloWorld - 2 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • csvan

      You have to add a main function which calls your function (doubleNumber()), and you should also add using namespace std; after the #include statements. A C++ program cannot (at least I know of no such thing) be run without a main function, because that is the actual function being called by the operating system!

  • Leonora A Quarcoo, US

  • Jon

    heres my code

  • Ravi

    Alex Sir,

    The following code doesn’t seem to work properly…
    It takes in all the instructions and data..but, doesn’t provide me with
    the result i.e .. the addition of the two numbers…
    plz help..

    • The problem is your function does not print the results of a+b, it just return it to main(), which doesn’t do anything with the result either.

    • Ivan

      There are of course more ways to solve the problem but i was into using the existing code….
      far too lazy… and its quite late.. XDD

  • gomezpcs

    In the beggining of this tutorials page you start of with DoPrint functions and you do a great job explaing it. all the sample code is complete and ready to compile. when i reach the Return Values and Parameters examples you have incomplete code that cannot compile? Why wasnt it written in complete ready to compile form?

    This gives me an error because u do not define X and y!!?

    1>---- Build started: Project: HelloWorld, Configuration: Debug Win32 ----
    1>Compiling…
    1>HelloWorld.cpp
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(22) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(22) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(23) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(23) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(24) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(24) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(28) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(28) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(30) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(30) : error C2065: ‘endl’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(31) : error C2065: ‘cout’ : undeclared identifier
    1>c:\c++2008\helloworld\helloworld\helloworld.cpp(31) : error C2065: ‘endl’ : undeclared identifier
    1>Build log was saved at “file://c:\C++2008\HelloWorld\HelloWorld\Debug\BuildLog.htm”
    1>HelloWorld - 12 error(s), 0 warning(s)
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    What gives? Am I an idiot? Or is there a reason y u didnt write the code out completely?

    • If you look at the errors your compiler is telling you, it’s not complaining about x and y, it’s complaining that it doesn’t know what cout and endl are. In order to define those, you have to #include and use the “using namespace std;” line.

      I fixed the example and made it a complete program so it will compile.

  • Hasan

    Peace be upon you

    It’s good place to learn and good exam

    However it’s my answer for question number 5

  • Leonora A Quarcoo, US

    i am having problems with this code can Alex please can you help
    tell me what i am doing wrong thanks
    the line cout Double number (

    • It look like you put your Doublenumber() function right in the middle of your main() function. Functions can’t be nested in C++.

      Just move Doublenumber() above main() and you will be one step closer.

      Also, when you call Doublenumber, it should be like this: Doublenumber(x)

  • NeoLogic

    I’m a complete n00b when it comes to programming.. I find it very interested how there are many different ways of getting the same work done.
    My answer to question 5 is totally different, but still works: I just think my way could be considered Bloatware. I’ll just have to learn how to be
    more effecient.

    int doubleNumber(int x, int y)
    {
    return x * y;
    }

    Anyway, I love your tutorials. I tried learning Pascal from a text book. I gave up before the first chapter. I think I might have a change using your tutorials,

    Thanks!

  • Masss

    Hi Alex,

    I was just doing question 5 of the quiz like everyone else, but the problem is that when I input a number the window closes once immediately after it displays the answer. I know you have to add the statements like cin.get(); cin.clear(); and cin.ignore(255, ‘/n’);, however, it does doesn’t prevent it from happening. Heres my coding.

    I tried adding cin.get, as I have commented. THANKS

  • josh

    i’m dong question 5 how you said. At the moment it looks like this:

    #include

    int doublenumber(int x)
    {
    return 2*x;
    }
    int main ()
    {
    using namespace std;
    int x;

    cin >> x;

    cout

    But all I get when I run and build it is the hello world program.
    I keep writing these things but it never does what i want it to.
    Would you happen to know why it is doing this and how the problem could be solved?

    • It sounds to me like you’re compiling and executing the wrong program. Many IDEs let you have multiple projects open simultaneously -- however, only one project will be active/selected, and this is the one that will compile/execute. Make sure you have your doublenumber project active. Usually active projects have their names in bold.

  • Dan

    Great tutorials thus far. Question on Quiz #5 for you. Your solution obviously works fine:

    int doubleNumber(int x)   
    {   
        return 2 * x;   
    }   
      
    int main()   
    {   
        using namespace std;   
        int x;   
        cin >> x;   
        cout < < doubleNumber(x) << endl;   
        return 0;   
    }
    But -- when I do my solution, which is basically the same as yours but listed in a different order:
    int main(){
    	using namespace std; 
    	int x;
    	cin >> x;
    	cout < < doubleNumber(x) << endl;
    	return 0;
    }
    
    int doubleNumber(int x){   
        return 2 * x;   
    }
    I get a compiler error in MS Visual Cpp 2008 Express [error C3861: ‘doubleNumber’: identifier not found]. Now, when I move my “doubleNumber(int x)” function so it appears ABOVE “main()” like so:
    int doubleNumber(int x){   
        return 2 * x;   
    }  
    
    int main(){
    	using namespace std; 
    	int x;
    	cin >> x;
    	cout < < doubleNumber(x) << endl;
    	return 0;
    }
    it works fine. So my question is: I thought the placement of “main()” within the code isn’t supposed to matter? I thought I read that somewhere in your tutorials… But regardless where I think I saw that, it doesn’t make sense that “main()” would have to appear at the bottom of every piece of Cpp code. Am I overlooking something? Thx, -Dan
    • Dan, when the compiler compiles your program, it reads through the files sequentially. This means if it hasn’t encountered doubleNumber() by the time you try to use doubleNumber(), then it will give you an error.

      There are two ways to fix this:
      1) Put your functions above main()
      2) Use a function prototype. This means, put the function declaration int doubleNumber(int x); above main(), and leave the actual function definition below main(). That way, when the compiler encounters doubleNumber(), it will know what to expect, even if you haven’t actually defined how doubleNumber() is implemented yet.

      • Dan

        Thanks for the feedback, Alex. I understand what you’re saying.

        So generally speaking, when Cpp developers write their code, (the assumption I’m making here is that) they’re always putting their functions above “main()”? I would think that, by doing your fix #2 -- i.e. using a function prototype for every function -- that would create a lot of extra lines of code, especially when you get into software that has thousands of lines of code.

        So the practice among Cpp developers is to have “main()” defined at the bottom of all Cpp code?

        • When developing single-file programs, yes. But when you get into multi-file programs, things become a bit more complex. In the case of multi-file programs, the typical way of doing this is to put the function prototypes in a header file, and then #include the header file wherever you need access to those functions. I cover this in more detail in section 1.9 -- header files

          • derpasaurus

            Do you go over function initialization? (actually, I have no idea  about the correct terminology, but see below) eg.

            Also, should function or methods be used as default? Why/why not? (Meaning, should we put our function/method inside a class or not.)

            • Alex

              This isn’t called “function initialization”, it’s called a forward declaration. And yes, we cover it later in this chapter. 🙂

              You should use both functions and methods (functions inside a class) as appropriate. If the function belongs to a class, put it inside the class. If it doesn’t, don’t. By the time you learn about classes, you’ll likely understand what to do.

Leave a Comment

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