-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCall_by_and_reference.cpp
82 lines (61 loc) · 2.12 KB
/
Call_by_and_reference.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Introduction
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters received by function are called formal parameters.
Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller.
Call by Reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.
*/
// Call by Value
#include <bits/stdc++.h>
using namespace std;
int Change_value(int number)
{
return number + 5;
}
int main()
{
cout << "\nExample of call By value\n";
int number;
cout << "\nEnter any random Integer Value : ";
cin >> number;
Change_value(number);
cout << "Printing The number after calling function change value\n ";
cout << number << endl;
return 0;
}
// Call by Reference
#include <bits/stdc++.h>
using namespace std;
int Change_value1(int &number)
{
return number + 5;
}
int main()
{
cout << "\nExample of call By reference\n";
int number;
cout << "\nEnter any random Integer Value : ";
cin >> number;
Change_value1(number);
cout << "Printing The number after calling function change value\n ";
cout << number << endl;
return 0;
}
// Example 2 of Call by Reference
#include <bits/stdc++.h>
using namespace std;
int main(){
// call by Value
cout<<"Call by Value"<<endl;
int x = 50;
int y = x;
cout << "x = " << x << ", y = " << y << endl;
x += 10;
cout<< "x = " << x << ", y = " <<y << endl;
// call by Reference
cout<<"\nCall by Reference"<<endl;
int *z = &x;
cout << "x = " << x << ", y = " << y << ", z = " << *z << endl;
*z += 10;
cout<< "x = " << x << ", y = " << y << ", z = " << *z << endl;
}