Passing Parameters
Learn how we can pass values to the functions in C++.
Passing methods
Values can be passed to a function through two methods.
Pass by value: Creates a copy of the variable being passed. Any change to the copy is not reflected in the original.
Pass by reference: Creates an alias of the variable being passed. Alias is not a new variable but instead a new name referring to the same memory location as that of the variable being passed. Any change is reflected in the original.
Arguments passed by value
In C++, by default, variables are passed by value to functions. This means that a copy of the data is made and passed to the function.
#include <iostream>using namespace std;void interchange(int arg1, int arg2) // Passing parameters by value{cout << "Argument 1 : " << arg1 << endl;cout << "Argument 2 : " << arg2 << endl;int temp = arg2; // Creating a variable temp and setting equal to arg2arg2 = arg1; // Setting the value of arg2 equal to arg1arg1 = temp; // Setting the value of arg1 equal to temp which is equal to arg2cout << "Argument 1 : " << arg1 << endl;cout << "Argument 2 : " << arg2 << endl;}int main(){int num1 = 4;int num2 = 5;cout << "Number 1 : " << num1 << endl;cout << "Number 2 : " << num2 << endl;interchange(num1, num2); // Calling the function interchange with parameters num1,num2cout << "Number 1 : " << num1 << endl;cout << "Number 2 : " << num2 << endl;return 0;}
Let’s now reflect on what happened in the above code. We create a function named interchange(int arg1, int arg2) that takes two integer arguments, arg1 and arg2 as parameters and swaps their values within the function. However, since the parameters are passed by value, the changes made to arg1 and arg2 inside the function, do not affect the original variables num1 and num2 in the main function.
Here’s an overview of the code flow, as illustrated in the diagram above:
In the
mainfunction,num1is initialized to4andnum2to5, and then we print their values.We then call the
interchangefunction withnum1andnum2as arguments. As they are passed by value, a copy ofnumandnum2is created and passed to the function as parameters.Inside the
interchangefunction, the values ofarg1andarg2are printed, and then we swap the values of these variables using a temporary variabletemp. We then print the values of these variables again. ...