-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3_references.cpp
More file actions
100 lines (77 loc) · 2.26 KB
/
3_references.cpp
File metadata and controls
100 lines (77 loc) · 2.26 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
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
#include <iostream>
using namespace std;
void hardSwap (int& first, int& second)
{
int temp = first;
first = second;
second = temp;
}
void swap2 (int *first, int *second)
{
int temp = *first;
first = second;
*second = temp;
}
void swap (int first, int second)
{
int temp = first;
first = second;
second = temp;
}
void pointerSwap (int *first, int *second)
{
int temp = *first;
*first = *second;
*second = temp;
}
int main(){
/*
* There are two types of references: (hard) reference & and pointer *
* Pointers "pointing" to a location (physical address) in memory where variable is store
* Reference is working directly with the variable on a specific address
* When passing varibale (not a reference) to a function a local copy is created for teh function
* To speed up your programs and work more efficiantly work with refrences and pointers
*/
//declare local variable in main function
int x = 1, y = 2;
//create a general pointer
int *px;
//an address is assign a pointer
cout << px << endl;
//no value has been assigned yet
cout << *px << endl;
//assign a reference address to pointer
px = &x;
//the address has changed since the pointer is poiting to a different (new) variable
cout << px << endl;
//pointer is poiting to a value
cout << *px << endl;
//to access a value what pointer px is pointing to you have dereference a pointer
//to dereference a pointer add a * infront of pointer
*px = 3;
//address doesnt change
cout << px << endl;
//only the value was chnaged - the address stayed same
cout << *px << endl;
int &ry = y;
//to access value from a reference
ry = 4;
cout << ry << endl;
int x1 = 5;
int x2 = 10;
cout << "x1: " << x1 << endl;
cout << "x2: " << x2 << endl;
swap( x1, x2 );
cout << "x1: " << x1 << endl;
cout << "x2: " << x2 << endl;
hardSwap( x1, x2 );
cout << "x1: " << x1 << endl;
cout << "x2: " << x2 << endl;
pointerSwap( &x1, &x2 );
cout << "x1: " << x1 << endl;
cout << "x2: " << x2 << endl;
swap2 ( px, &x2 );
cout << "x1: " << x1 << endl;
cout << "x2: " << x2 << endl;
return 0;
}