-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreferences.cpp
52 lines (40 loc) · 1.13 KB
/
references.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
#include <iostream>
using std::cout, std::endl;
#define p(x) cout << x << endl; // macro to print variables
// call by value
void reduce(int a){
// creates copy of a inside the method
a--; // it will not change the value of `a`
// because its just temporary variable in memory
}
// call by reference
void increment(int& a){
// its reference of `a`
a++; // so it will increment `a`
}
// also call by reference
void add(int *a){
// its pointer of `a`
(*a)++; // so it will increment `a`
// we use (*a) so it will increment the value
// otherwise, it will increment the address
}
int main(){
int a = 10;
// reference does not creates another variable in memory
// unlike pointers, its just reference to `a` value
int& ref = a;
p(ref); // 10
add(&a);
p(a); // 11
increment(a);
p(a); // 12
reduce(a);
p(a); // still 12, because it's call by value method
// references cannot be changed
// so it will just set a to b (a=25), not turning into `b` reference
int b = 25;
ref = b;
cout << "ref: " << ref << endl;
cout << "a: " << a << endl;
}