In the previous lesson, we learned that we could have a function return a value back to the function’s caller. We used that to create a modular getValueFromUser function that we used in this program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> int getValueFromUser() { std::cout << "Enter an integer: "; int input{}; std::cin >> input; return input; } int main() { int num { getValueFromUser() }; std::cout << num << " doubled is: " << num * 2 << '\n'; return 0; } |
However, what if we wanted to put the output line into its own function as well? You might try something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> int getValueFromUser() { std::cout << "Enter an integer: "; int input{}; std::cin >> input; return input; } // This function won't compile void printDouble() { std::cout << num << " doubled is: " << num * 2 << '\n'; } int main() { int num { getValueFromUser() }; printDouble(); return 0; } |
This won’t compile, because function printDouble doesn’t know what identifier num is. You might try defining num as a variable inside function printDouble():
1 2 3 4 5 |
void printDouble() { int num{}; // we added this line std::cout << num << " doubled is: " << num * 2 << '\n'; } |
While this addresses the compiler error and makes the program compile-able, the program still doesn’t work correctly (it always prints “0 doubled is: 0”). The core of the problem here is that function printDouble doesn’t have a way to access the value the user entered.
We need some way to pass the value of variable num to function printDouble so that printDouble can use that value in the function body.
Function parameters and arguments
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 some 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. Function parameters work almost identically to variables defined inside the function, but with one difference: they are always initialized with a value provided by the caller of the function.
Function parameters are defined in the function declaration by placing them in between the parenthesis after the function identifier, with multiple parameters being separated by commas.
Here are some examples of functions with different numbers of parameters:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// This function takes no parameters // It does not rely on the caller for anything void doPrint() { std::cout << "In doPrint()\n"; } // This function takes one integer parameter named x // The caller will supply the value of x void printValue(int x) { std::cout << x << '\n'; } // This function has two integer parameters, one named x, and one named y // The caller will supply the value of both x and y int add(int x, int y) { return x + y; } |
An argument is a value that is passed from the caller to the function when a function call is made:
1 2 3 |
doPrint(); // this call has no arguments printValue(6); // 6 is the argument passed to function printValue() add(2, 3); // 2 and 3 are the arguments passed to function add() |
Note that multiple arguments are also separated by commas.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#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 << '\n'; std::cout << y << '\n'; } int main() { printValues(6, 7); // This function call has two arguments, 6 and 7 return 0; } |
When function printValues is called with arguments 6 and 7, printValues‘s parameter x is created and initialized with the value of 6, and printValues‘s parameter y is created and initialized with the value of 7.
This results in the output:
6 7
Note that the number of arguments must generally match the number of function parameters, or the compiler will throw an error. The argument passed to a function can be any valid expression (as the argument is essentially just an initializer for the parameter, and initializers can be any valid expression).
Fixing our challenge program
We now have the tool we need to fix the program we presented at the top of the lesson:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> int getValueFromUser() { std::cout << "Enter an integer: "; int input{}; std::cin >> input; return input; } void printDouble(int value) // This function now has an integer parameter { std::cout << value << " doubled is: " << value * 2 << '\n'; } int main() { int num { getValueFromUser() }; printDouble(num); return 0; } |
In this program, variable num is first initialized with the value entered by the user. Then, function printDouble is called, and the value of argument num is copied into the value parameter of function printDouble. Function printDouble then uses the value of parameter value.
Using return values as arguments
In the above problem, we can see that variable num is only used once, to transport the return value of function getValueFromUser to the argument of the call to function printDouble.
We can simplify the above example slightly as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> int getValueFromUser() { std::cout << "Enter an integer: "; int input{}; std::cin >> input; return input; } void printDouble(int value) { std::cout << value << " doubled is: " << value * 2 << '\n'; } int main() { printDouble(getValueFromUser()); return 0; } |
Now, we’re using the return value of function getValueFromUser directly as an argument to function printDouble!
Although this program is more concise (and makes it clear that the value read by the user will be used for nothing else), you may also find this “compact syntax” a bit hard to read. If you’re more comfortable sticking with the version that uses the variable instead, that’s fine.
A warning about function argument order of evaluation
The C++ specification does not define whether arguments are matched with parameters in left to right order or right to left order. When copying values, order is of no consequence. However, if the arguments are function calls, then this can be problematic:
1 |
someFunction(a(), b()); // a() or b() may be called first |
If the architecture evaluates left to right, a() will be called before b(). If the architecture evaluates right to left, b() will be called before a(). This may or may not be of consequence, depending on what a() and b() do.
If it is important that one argument evaluate first, you should explicitly define the order of execution, like so:
1 2 3 4 |
int avar{ a() }; // a() will always be called first int bvar{ b() }; // b() will always be called second someFunction(avar, bvar); // it doesn't matter whether avar or bvar are copied first because they are just values |
Warning
The C++ specification does not define whether function calls evaluate arguments left to right or right to left. Take care not to make function calls where argument order matters.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> // add() takes two integers as parameters, and returns the result of their sum // The values of x and y are determined by the function that calls add() int add(int x, int y) { return x + y; } // main takes no parameters int main() { std::cout << add(4, 5) << '\n'; // Arguments 4 and 5 are passed to function add() return 0; } |
Execution starts at the top of main. When add(4, 5)
is evaluated, function add is called, with parameter x being initialized with value 4, and parameter y being initialized with value 5.
The return statement in function add evaluates x + y to produce the value 9, which is then returned back to main. This value of 9 is then sent to std::cout to be printed on the console.
Output:
9
In pictorial format:

More examples
Let’s take a look at some more function calls:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#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) << '\n'; // within add() x=4, y=5, so x+y=9 std::cout << add(1 + 2, 3 * 4) << '\n'; // within add() x=3, y=12, so x+y=15 int a{ 5 }; std::cout << add(a, a) << '\n'; // evaluates (5 + 5) std::cout << add(1, multiply(2, 3)) << '\n'; // evaluates 1 + (2 * 3) std::cout << add(1, add(2, 3)) << '\n'; // evaluates 1 + (2 + 3) return 0; } |
This program produces the output:
9 15 10 7 6
The first statement is straightforward.
In the second statement, the arguments are expressions that get evaluated before being passed. In this case, 1 + 2 evaluates to 3, so 3 is copied to parameter x. 3 * 4 evaluates to 12, so 12 is copied to parameter y. add(3, 12) resolves to 15.
The next pair of statements is relatively easy as well:
1 2 |
int a{ 5 }; std::cout << add(a, a) << '\n'; // evaluates (5 + 5) |
In this case, add() is called where the value of a is copied into both parameters x and y. Since a has value 5, add(a, a) = add(5, 5), which resolves to value 10.
Let’s take a look at the first tricky statement in the bunch:
1 |
std::cout << add(1, multiply(2, 3)) << '\n'; // evaluates 1 + (2 * 3) |
When the function add is executed, the program needs to determine what the values for parameters x and y are. x is simple since we just passed it the integer 1. To get a value for parameter y, it needs to evaluate multiply(2, 3) first. The program calls multiply and initializes z = 2 and w = 3, so multiply(2, 3) returns the integer value 6. That return value of 6 can now be used to initialize the y parameter of the add function. add(1, 6) returns the integer 7, which is then passed to std::cout for printing.
Put less verbosely:
add(1, multiply(2, 3)) evaluates to add(1, 6) evaluates to 7
The following statement looks tricky because one of the arguments given to add is another call to add.
1 |
std::cout << add(1, add(2, 3)) << '\n'; // evaluates 1 + (2 + 3) |
But this case works exactly the same as the prior case. add(2, 3) resolves first, resulting in the return value of 5. Now it can resolve add(1, 5), which evaluates to the value 6, which is passed to std::cout for printing.
Less verbosely:
add(1, add(2, 3)) evaluates to add(1, 5) => evaluates to 6
Conclusion
Function parameters and return values are the key mechanisms by which functions can be written in a reusable way, as it allows us to write functions that can perform tasks and return retrieved or calculated results back to the caller without knowing what the specific inputs or outputs are ahead of time.
Quiz time
Question #1
What’s wrong with this program fragment?
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> void multiply(int x, int y) { return x * y; } int main() { std::cout << multiply(4, 5) << '\n'; return 0; } |
Question #2
What two things are wrong with this program fragment?
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int multiply(int x, int y) { int product{ x * y }; } int main() { std::cout << multiply(4) << '\n'; return 0; } |
Question #3
What value does the following program print?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> int add(int x, int y, int z) { return x + y + z; } int multiply(int x, int y) { return x * y; } int main() { std::cout << multiply(add(1, 2, 3), 4) << '\n'; return 0; } |
Question #4
Write a function called doubleNumber() that takes one integer parameter. The function should return double the value of the parameter.
Question #5
5) Write a complete program that reads an integer from the user, doubles it using the doubleNumber() function you wrote in the previous quiz, and then prints the doubled value out to the console.
![]() |
![]() |
![]() |
In "More Examples" there's a sentence "The following statement looks tricky because one of the parameters given to add is another call to add." it should be "arguments" instead of "parameters".
In "More Examples" there's a sentence "The following statement looks tricky because one of the parameters given to add is another call to add.". It should be "arguments" instead of "parameters".
Thanks, fixed!
My attempt at answering question 5 - functions calling function, calling functions.
"When copying values, order is of no consequence. However, if the arguments are function calls, then this can be problematic"
Why? If the argument is an expression like 3*value there is no problem, if the argument is a function call with the same expression in it, theres also no problem in order. But if the argument is a function call that receives user input with cin, the order somehow matters. Why? I dont understand, it should evaluate, get the value, and then copy it and it should match the parameters no matter the order. Can someone explain me why is this?
Calling pure functions (Functions that don't access anything non-const objects from their local variables (that includes parameters)), is safe no matter the order, because those functions always do the same.
If a function has a side effect (For example printing or reading user input), the call order changes the program's behavior.
but
Therefore
I am sorry but I didn't get it. Why a() will be called first?? Is that because it has been written first?
Code is executed from top to bottom
Okay thanks!
If they created a book with all These chapters and examples and the way each topic is described and explained this book will be the best cpp book out there. Great job guys.
Time is money. The time taken to write these tutorials are supported by ads, and donations. If the author made book, everybody couldn't get this recourse for free.
You can print offline copy for your personal use :)
Is there any way for a function to accept a multi type parameter or CAST a parameter to a specific type ?
for example,
void postmsg(std::string msg)
{
std::cout << msg;
}
postmsg("Hello world") should work fine
but what if we passed an integer postmsg(4) and wanted to display 4 on screen ?
how do we tell postmsg function to convert the passed parameter into string type ?
`postmsg(std::to_string(4))`, templates, or function overloads
----------------
----------------
void version
#include <iostream>
int doubleNumber(int x)
{
return x * 2;
};
void getValueFromUser()
{
std::cout << "Enter an integer: ";
int input{};
std::cin >> input;
std::cout<< doubleNumber(input);
}
int main()
{
getValueFromUser();
return 0;
}
---------------------------------------------------
int version
#include <iostream>
int doubleNumber(int x)
{
return x * 2;
};
int getValueFromUser()
{
std::cout << "Enter an integer: ";
int input{};
std::cin >> input;
return doubleNumber(input);
}
int main()
{
std::cout<<getValueFromUser();
return 0;
}
why arguments order not matters for non-functions parameters?
e.g., subtract(5, 3) gives 2which is not equal to subtract(3, 5) gives -2, because order matters!
int subtract(int x, int y){
return x-y;
}
The order of parameters is always the same. Only the evaluation order of the arguments is unspecified.
> Function parameters and return values are the key mechanisms by which functions can be written in a reusable way, as it allows us to write functions that can perform tasks and return *retrieved or calculated results* back to the caller **without knowing what the specific inputs or outputs are ahead of time.**
I've read this three times already and don't get it, especially the part within the asteriks. Could someone tell me what this means?
This function doesn't know what value `i` has or which value it will return, ie. it works **without knowing what the specific inputs or outputs are ahead of time.**
It's returning a value that is calculated, ie. it returns *retrieved or calculated results*. "retrieved" would be if this function called another function.
Okay, that makes sense. Thank you!
Is there any plans in the further cpp standards to implement the javascript rest operator?
C++ has template parameter packs
Question to the author: Your example specifies "return 2 * x;", while my solution (and many others) implements it as "return x * 2;". What is the difference? Did you have any special reason for doing this, or is it just a habit? (Sorry for my English. I read much better than I write)
Output:
Write number: 5
Double of 5 is 10
There's no difference. I guess people who have a background in math prefer `2 * number`.
I don't think it influences anything, my result is also the same as yours "return x * 2;" instead of "return 2 * x;".
the More examples Section, would have been better suited for me at the top of the page.
i luv your website.
in fact I don't understand the FIX still. the introduction to the word, VALUE, just kicks me in the butt. i'm lopping on an error.
I tried to make it as simple as i could
You can simplify it further
You got some bad indentation skills.
I understand parameters and arguments better now..
Why do I have to define parameter types [like: function(INT parameter1)], can't C++ see what the type of the argument is, and so define the parameter as the same type automatically?
No, C++ will not automatically(implicitly) declare/initialize anything, it's the programmer's responsibility to do those things, which enables us to have full control over memory. This is the core feature of C++ which makes it the fastest/powerful programming language in the world and hence widely used in military devices(radars, GUIs, etc...).
First go through the basics, start from the introduction because these core things are already discussed in the introduction and first chapter.
Hi. I did the quiz this way. Is this any good? I feel like it's too complicated
Hey, a little late but I want to say that it looks almost the same as mine and mine works fine. Like they said there are multiple ways to end up at the same path in C++. Maybe there are better ways but we'll figure that out as we go!
Thanks for these great tutorials!
Suggestion for a tiny improvement: In section "More examples", replace "The first statement is straightforward." with "The first statement in the body of main() is straightforward." I was unsure whether the remark related to the statement in add().
This was my program for Question 5. Is this alright?
Yes, that is alright. However, for best practice, you always need to initialize variables with {}.
Otherwise, if the user inputs a variable non-integer value like words, it will cause an error, or it will display an invisible value instead. So with initializing value when the user inputs a non-integer value, it always sets to zero and prevents errors.
In the following snippet, can we say the add function arguments referred to here, are a nested function.
std::cout << multiply(add(1, 2, 3), 4) << '\n';
If so, we can say that all nested functions are always preformed first? Is it possible in C++ to nest more than once? If so is are there a limit?
ref.(a function in a function in another function)
I know I might be nitpicking, but " #include <iostream> " is missing from questions #1 and #2.
Thank you for making these lessons, they're great!
it was really nicely expalined
thanks a ton
I tried making the program for Question #5 in line with some of the other code we've seen here while trying to keep everything "modular"
Looks good :)
I'd like to thank you guys so much for this. I took an intro course and, most recently, an object-oriented programming course in college where we used C++ and then Visual C#. I was never able to properly understand arguments and parameters and so some of my projects became mangled messes where I had tried to find workarounds or, in some cases, they finally worked somehow but I didn't actually know why. I finally understand these concepts and now that I look back at my projects that suffered because of this, it's all suddenly so obvious. Thank you so much for explaining things so clearly and in a way that immediately allows one to grasp the logic behind the language.