-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9-REFERENCESinCpp.cpp
78 lines (62 loc) · 1.65 KB
/
9-REFERENCESinCpp.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
REFERENCES in C++
Reference is just an extension of pointers
References. are references to variables
int a = 5;
int* b = &a;
*b = 10; is the same as a = 10;
int& ref = a;
Here we created an alias
ref = 2; is the same as a = 2;
The reference is not a pointer is just an alias for a
The compiler will just see one variable a, the variable reference doesn't exist because it's just an alias
Ex:
void Increment (int value){
value++;
}
int main()
{
int a = 5;
Increment(a);
std::cout << a << std::endl;
std::cin.get();
}
In this case the value a is copied inside the variable value in the function Increment
Ex:
void Increment (int* value){ [MOD]
(*value)++; [MOD]
}
int main()
{
int a = 5;
Increment(&a); [MOD]
std::cout << a << std::endl;
std::cin.get();
}
In this case the address value of a is COPIED in value and the data at the memory address value is incremented.
I need to put parenthesis to (*value) because first I need to dereference and then I need to increment the value.
x:
void Increment (int& value){ [MOD]
value++; [MOD]
}
int main()
{
int a = 5;
Increment(a); [MOD]
std::cout << a << std::endl;
std::cin.get();
}
In this case I pass a to the function Increment that takes it as a reference
Everything you can do with references you can also do with pointers, but references are a lot cleaner than pointers
What you CAN'T DO with references is this
int a = 5;
int b = 8;
int& ref = a;
ref = b; NOT POSSIBLE to change a reference
This will eventually produce: a=b; so at the end a=8, b=8.
With pointers I can do:
int a = 5;
int b = 8;
int* ref = &a;
*ref = 2; corresponds to a = 2;
ref = &b; ref now is pointing to b
*ref = 4; corresponds to b = 4;