-
Notifications
You must be signed in to change notification settings - Fork 7
/
call_by_value_and_ref.cpp
42 lines (37 loc) · 1.23 KB
/
call_by_value_and_ref.cpp
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
36
37
38
39
40
41
42
#include<iostream>
using namespace std;
int sum(int a, int b){
int c = a + b;
return c;
}
// This will not swap a and b
void swap(int a, int b){ //temp a b
int temp = a; //4 4 5
a = b; //4 5 5
b = temp; //4 5 4
}
// Call by reference using pointers
void swapPointer(int* a, int* b){ //temp a b
int temp = *a; //4 4 5
*a = *b; //4 5 5
*b = temp; //4 5 4
}
// Call by reference using C++ reference Variables
// int &
void swapReferenceVar(int &a, int &b){ //temp a b
int temp = a; //4 4 5
a = b; //4 5 5
b = temp; //4 5 4
// return a;
}
int main(){
int x =4, y=5;
// cout<<"The sum of 4 and 5 is "<<sum(a, b);
cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl;
// swap(x, y); // This will not swap a and b
// swapPointer(&x, &y); //This will swap a and b using pointer reference
swapReferenceVar(x, y); //This will swap a and b using reference variables
// swapReferenceVar(x, y) = 766; //This will swap a and b using reference variables
cout<<"The value of x is "<<x<<" and the value of y is "<<y<<endl;
return 0;
}