Function Arguments in C++
Overview
In this article, we will learn about how we can make our functions dynamic. If you have read the previous article "Introduction to function", you must have noticed that the function ( BirthdayGreeting( ) ) gives a static output.
Function arguments are essential in programming because they provide a way to pass data to a function, allowing it to perform tasks with varying inputs.
Argument acts as input to the function. ✌️
Example: Function without Argument
Let's try to understand with the help of an example where we write a function to multiply two numbers.
Code
#include <iostream>
using namespace std;
// function definition
void MultiplyNumbers() {
int number1 = 8;
int number2 = 6;
int result = number1 * number2;
cout << "Product of " << number1 <<" and "<< number2 << " is " << result << endl;
}
int main() {
// function call
MultiplyNumbers();
return 0;
}
In this code, the MultiplyNumbers() function multiplies two predefined numbers (number1 = 8 and number2 = 6) and prints the result. When you run this program, you'll see the output:
Output
Product of 8 and 6 is 48
The MultiplyNumbers() function will not be flexible for other inputs apart from specifically calculating the multiplication of two fixed numbers 6 and 8.
Now, we'll explore how to make our function more dynamic.
We can make functions which take input (known as arguments) and provide output (known as the return value). This allows us to create more versatile and adaptable functions. Isn't it super cool? 😀
Function with Arguments
Now we will see how we can pass inputs to a function.
We have 3 ways by which we can pass arguments to a function:
- Pass By Value
- Pass By Reference
- Pass By Address / Pass by pointer): This we will cover later when we will study pointers.
Two terms that are commonly used in C++: Actual Parameters and Formal Parameters.
- Actual Parameters are the values that are being passed to the function. Actual parameters are those parameters that are specified in the calling function.
- Formal Parameters are the variables that are defined in the function definition. Formal parameters are those parameters that are declared in the called function.
Now, we are ready to learn about Pass by value and Pass by reference.
Pass by Value
In Pass By Value, the value of an actual parameter is copied to the formal parameters. The changes made to the formal parameters inside the function definition will not be reflected in the variables of the actual parameters. In C++ by default, the arguments are passed by value.
Imagine you have a revision notebook, and you want to share your notes with a friend. In a "pass by value" scenario, you make a photocopy of the notes and give the copy of notes to your friend.
So, you're essentially making a copy of the variable's value and passing that copy to the function. The original variable remains unchanged. Just like the photocopy of the notes, the function gets its own copy of the data, and any changes made inside the function won't affect the original variable.
Will Pass by Value take more space(memory)??
Hint
Yes, it will. Pass by value uses more memory as for the same variable, 2 memory locations are made.
#include <iostream>
using namespace std;
void Address(int a) {
cout << "Address of 'a' variable in Address() function: " << &a <<
endl;
}
int main() {
int a = 10;
cout << "Address of 'a' variable in main function: " << &a << endl;
Address(a);
return 0;
}
Output of the above code:
Address of 'a' variable in main function: 0x7ffc0b87f224
Address of 'a' variable in Address() function: 0x7ffc0b87f20c
Note: To access the memory address, & operator is used.
If you carefully notice the output, the address of variable a is different in both functions.
When the control is transferred from the main function to the Address function, a new memory location is made for the formal parameter, and the value of the actual parameter is copied into that. On printing the address of the variable in the main and the Address function we obtain different values. Hence, we can say that the copy of the actual parameter variable is passed into the formal parameter.
Pass by Reference
First, let's see what we mean by reference.
A reference variable is a nickname for some other variable. To declare a reference variable, we use the unary operator &.
Note: To declare a reference variable, add the & operator after the type.
int a = 5; // this declares variable a
int &b = a; //// this declares b as a reference to a
In the above example, b is now a reference to a. (They are both referring to the SAME storage location in memory).
The notation can become confusing when different sources place the & differently. The following three declarations are equivalent:
int &r = n;
int& r = n;
int & r = n;
In Pass By Reference, the reference of an actual parameter is copied into the formal parameters. So in the function, the reference is used to access the actual value of the argument. Therefore any changes made inside the function will be reflected in the variables of actual parameters. To pass a variable by reference '&' symbol is used.
Imagine you have a revision notebook, and you want to share your notes with a friend. In a "pass by reference" scenario, you give your original notes to your friend.
Will Pass by Reference save space(memory)??
Hint
Pass by reference saves memory as the reference of the variable is used. There is no new memory location created for the formal parameters. Rather the reference to the memory location of the actual parameter is used.
#include <iostream>
using namespace std;
//Notice we have used '&' this time in the function declaration.
//By using '&', We are using a reference to the variable a.
void Address(int &a) {
cout << "Address of 'a' variable in Address() function: " << &a <<
endl;
}
int main() {
int a = 10;
cout << "Address of 'a' variable in main function: " << &a << endl;
Address(a);
return 0;
}
Output of the above code:
Address of 'a' variable in main function: 0x7ffc0b886ccc
Address of 'a' variable in Address() function: 0x7ffc0b886ccc
If you carefully notice the output, the address of variable a is exactly the same in both functions.
When the control is transferred from the main function to the Address function, there is no new memory location created for the formal parameters. Rather the formal parameter is used to refer to the memory location of the actual parameter. On printing the address of the variable 'a' in both functions we get the same result.
Note: Changes made inside the function is reflected outside the function also in pass by reference method.
Let's see one more concept:
Default Argument
It is basically a value provided in the function declaration that is automatically assigned by the compiler if the caller of the function doesn't provide a value while calling the argument.
Imagine you are at a restaurant, and you want to order a burger. The default configuration of the burger includes a patty, cheese, and tomato (Default argument). If you don't customize your burger you will get this default burger automatically. Otherwise, you can add toppings and customize your burger according to your choice.
I hope you get the idea. If a function is called by passing arguments, those arguments are used by the function. But if arguments are not passed while calling a function, the default values are used.
Let's see an example to understand this concept.
#include <iostream>
using namespace std;
void Display(char c = '*', int n = 1)
{
for(int i = 1; i <= n; i++)
{
cout << c;
}
cout << endl;
}
int main()
{
cout << "No argument passed: ";
Display();
cout << "First argument passed: ";
Display('+');
cout << "Both argument passed: ";
Display('@', 5);
return 0;
}
Output
No argument passed: *
First argument passed: +
Both argument passed: @@@@@
Explanation:
- In the above program, you can see the default value assigned to the arguments void Display(char = '*', int = 1);.
- At first, the Display( ) function is called without passing any arguments. In this case, the Display( ) function used both default arguments c = '*' and n = 1.
- Then, only the first argument is passed using the function second time. In this case, the function does not use the first default value passed. It uses the actual parameter passed as the first argument c = '+' and takes the default value n = 1 as its second argument.
- When Display( ) is invoked for the third time passing both arguments, default arguments are not used. So, the values of c = '@' and n = 5 are used.
Example: Function with Arguments
Here's a little modification to the MultiplyNumbers() function we previously created.
Code
#include <iostream>
using namespace std;
// function definition
void MultiplyNumbers()( int number1, int number2 ) {
int result = number1 * number2;
cout << "Product of " << number1<<" and "<<number2 << " is " << result << endl;
}
int main() {
// function call
MultiplyNumbers(6,8);
MultiplyNumbers(5,6);
MultiplyNumbers(9,29);
return 0 ;
}
Output
Product of 8 and 6 is 48
Product of 8 and 6 is 30
Product of 8 and 6 is 261
In the above code, we modified the MultiplyNumbers() function to accept two arguments (number1 and number2). These arguments represent the numbers we want to multiply.
Note: We have added arguments inside parentheses ().
Working Of Program
Here's how this program works:
When the MultiplyNumbers( ) function is called, the control of the program jumps to that function. This time, we are passing 6 and 8 as an argument to the function in the first function call. These values are now assigned to the variables number1 and number2 inside the function.
Now, by changing the input numbers, we can use the same function to calculate the product for different scenarios.
Note: We can pass multiple argument to a function by separating them with commas.
Quiz
#include <iostream>
using namespace std;
// function definition
void MinusTen(int number) {
int result = number + 20;
cout << result <<" ";
}
int main() {
// function call
MinusTen(100);
MinusTen(20);
return 0;
}
#include <iostream>
using namespace std;
// function definition
void AddTen() {
int number = 20;
int result = number + 10;
cout << result <<" ";
}
int main() {
// function call
AddTen(100);
AddTen(20);
return 0;
}
Practice Problem
Write a C++ program to input any integer from the user and find the cube of the given number using a function.
Input
Input any number: 5
Output
Cube of the number is 125
Solution
Solution
#include <iostream>
using namespace std;
void cube (int num){
int answer = num * num * num;
cout << "Cube of the number is " << answer;
}
int main(){
int num;
/* Input number to find cube from user */
cout << "Enter any number: " << endl;
cin >> num;
cube(num);
return 0;
}
See you in the next article with more energy and excitement ✌️ till then Happy Learning !! 😀