1
+ #include < iostream>
2
+
3
+ using namespace std ;
4
+
5
+ int getIncValue (int x)
6
+ {
7
+ return x * 100 ;
8
+ }
9
+
10
+ int &getIncValue2 (int &x)
11
+ {
12
+ return x;
13
+ }
14
+
15
+ int main ()
16
+ {
17
+ int a = 10 ;
18
+ int &ra = a;
19
+
20
+ // ra is just a reference to a, meaning its just an
21
+ // another name for 'a'. Therefore, it has the same
22
+ // value and the same memory address as of a.
23
+
24
+ cout << " a: " << a << endl;
25
+ cout << " ra: " << ra << endl;
26
+
27
+ cout << " &a: " << &a << endl;
28
+ cout << " &ra: " << &ra << endl;
29
+
30
+ // These are also called 'l-value' references.
31
+ // Since we can get the memory associated with these
32
+ // variables.
33
+
34
+ a = getIncValue (a);
35
+
36
+ cout << " a: " << a << endl;
37
+ cout << " ra: " << ra << endl;
38
+
39
+ cout << " &a: " << &a << endl;
40
+ cout << " &ra: " << &ra << endl;
41
+
42
+ // Now
43
+
44
+ // this is not allowed because '20' is an r-value
45
+ // and we cannot get a reference to an r-value
46
+
47
+ // int &r = 20; // error
48
+
49
+ // however
50
+ // if there is a const in front, then we are allowed
51
+ // to get ref.
52
+
53
+ const int &r = 20 ;
54
+
55
+ cout << " &r: " << &r << endl;
56
+
57
+ // this happens because internally C++ creates a temp
58
+ // variable and assign the ref of temp to r.
59
+ // Like this,
60
+
61
+ int temp = 20 ;
62
+ int &x = temp;
63
+
64
+ // l-val references returned by function
65
+ // a value returned by a function, by default, is
66
+ // treated as an r-value. Therefore we cannot get
67
+ // a ref to that returned value.
68
+ // For example the below is incorrect and throws error.
69
+
70
+ // int &h = getIncValue(10); // r-value, need l-value
71
+
72
+ // However, if we make our function return the reference
73
+ // instead of the the regular value.
74
+ // It will be accepted!
75
+ // For example,
76
+
77
+ int &h = getIncValue2 (a); // accepted! because the fnction returns a ref.
78
+
79
+ // There is one more important topic that
80
+ // screwed my mind.
81
+
82
+ // Since the above function is just returning a referece
83
+ // to a. That means, the returned value is just another name
84
+ // for 'a'. And also the memory address is the same as 'a'.
85
+ // Therefore wrting like below is valid.
86
+
87
+ cout << endl
88
+ << endl;
89
+
90
+ cout << " a: " << a << endl;
91
+ cout << " &a: " << &a << endl;
92
+ cout << " h: " << h << endl;
93
+ cout << " &h: " << &h << endl;
94
+
95
+ // now,
96
+
97
+ getIncValue2 (a) = 8888 ;
98
+
99
+ cout << " a: " << a << endl;
100
+ cout << " &a: " << &a << endl;
101
+ cout << " h: " << h << endl;
102
+ cout << " &h: " << &h << endl;
103
+ }
0 commit comments