-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15callbyref.cpp
More file actions
35 lines (33 loc) · 1.08 KB
/
Copy path15callbyref.cpp
File metadata and controls
35 lines (33 loc) · 1.08 KB
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
26
27
28
29
30
31
32
33
34
35
#include<iostream>
using namespace std;
void swap(int a, int b) // this method would not work as the variables changing here doesn't affect the actual parameters
{
int temp = a;
a = b;
b = temp;
}
void swapWithPointer(int *a, int *b) //this will work as it takes the address of actual parameters
{
int temp = *a;
*a = *b;
*b = temp;
}
void swapWithReferenceVar(int &a, int &b) //using reference variable where 2 variables point to a single value simultaneously
{
int temp = a; //no dereferencing
a = b;
b = temp;
}
int main()
{
int x = 4, y = 6;
cout<<"The value of x before swap is "<<x<<" and of y is "<<y<<endl;
swap(x, y); //this method won't work
swapWithPointer(&x, &y); // this will work as the address is passed to the formal parameters
cout<<"The value of x after swap is "<<x<<" and of y is "<<y<<endl;
int i = 3, j = 5;
cout<<"The value of i before swap is "<<i<<" and of j is "<<j<<endl;
swapWithReferenceVar(i, j); //no address
cout<<"The value of i after swap is "<<i<<" and of j is "<<j<<endl;
return 0;
}