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 created 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
main
function,num1
is initialized to4
andnum2
to5
, and then we're printing their values.We then call the
interchange
function withnum1
andnum2
as arguments. As they are passed by value, a copy ofnum
andnum2
is created and passed to the function as parameters.Inside the
interchange
function, the ...