-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotes_8_l_val_ref.cpp
More file actions
103 lines (73 loc) · 2.37 KB
/
notes_8_l_val_ref.cpp
File metadata and controls
103 lines (73 loc) · 2.37 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
101
102
103
#include <iostream>
using namespace std;
int getIncValue(int x)
{
return x * 100;
}
int &getIncValue2(int &x)
{
return x;
}
int main()
{
int a = 10;
int &ra = a;
// ra is just a reference to a, meaning its just an
// another name for 'a'. Therefore, it has the same
// value and the same memory address as of a.
cout << "a: " << a << endl;
cout << "ra: " << ra << endl;
cout << "&a: " << &a << endl;
cout << "&ra: " << &ra << endl;
// These are also called 'l-value' references.
// Since we can get the memory associated with these
// variables.
a = getIncValue(a);
cout << "a: " << a << endl;
cout << "ra: " << ra << endl;
cout << "&a: " << &a << endl;
cout << "&ra: " << &ra << endl;
// Now
// this is not allowed because '20' is an r-value
// and we cannot get a reference to an r-value
// int &r = 20; // error
// however
// if there is a const in front, then we are allowed
// to get ref.
const int &r = 20;
cout << "&r: " << &r << endl;
// this happens because internally C++ creates a temp
// variable and assign the ref of temp to r.
// Like this,
int temp = 20;
int &x = temp;
// l-val references returned by function
// a value returned by a function, by default, is
// treated as an r-value. Therefore we cannot get
// a ref to that returned value.
// For example the below is incorrect and throws error.
// int &h = getIncValue(10); // r-value, need l-value
// However, if we make our function return the reference
// instead of the the regular value.
// It will be accepted!
// For example,
int &h = getIncValue2(a); // accepted! because the fnction returns a ref.
// There is one more important topic that
// screwed my mind.
// Since the above function is just returning a referece
// to a. That means, the returned value is just another name
// for 'a'. And also the memory address is the same as 'a'.
// Therefore wrting like below is valid.
cout << endl
<< endl;
cout << "a: " << a << endl;
cout << "&a: " << &a << endl;
cout << "h: " << h << endl;
cout << "&h: " << &h << endl;
// now,
getIncValue2(a) = 8888;
cout << "a: " << a << endl;
cout << "&a: " << &a << endl;
cout << "h: " << h << endl;
cout << "&h: " << &h << endl;
}