-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClass725.cpp
executable file
·101 lines (67 loc) · 1.75 KB
/
Class725.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//============================================================================
// Name : Class725.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
//============================================================================
// Name : Class725.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
void swap(int* p, int* q) { //exchanging the two values
int t = *p;
*p = *q;
*q = t;
}
void swap2(int* p, int* q) { //this confirms that pointers are passed by value
//set p point to q's value box and
//q point to p's value box
int* t;
t = p;
p = q;
q = t;
}
void swap3(int& r, int& s) {
int t;
t = r; //value box is referenced directly by the reference variable;
r = s; //you don't need a deference operator like the one for the pointer variable
s = t; //Reference variable is fixed; it can't change to refer to a different value box
}
void sample1() {
int* p1;
int* p2;
p1 = new int;
p2 = new int;
*p1 = 10;
*p2 = 20;
cout << *p1 << " " << *p2 << endl;
swap(p1, p2);
cout << *p1 << " " << *p2 << endl;
*p1 = 100;
*p2 = 200;
cout << endl;
cout << *p1 << " " << *p2 << endl;
swap2(p1, p2);
cout << *p1 << " " << *p2 << endl;
}
void sample2( ) {
//This is an example of call-by-reference
int n, m;
n = 10;
m = 20;
cout << endl;
cout << n << " " << m << endl;
swap3(n, m);
cout << n << " " << m << endl;
}
int main() {
sample1();
sample2();
return 0;
}