-
Notifications
You must be signed in to change notification settings - Fork 0
/
ch5_cpp_hard.cpp
61 lines (48 loc) · 1 KB
/
ch5_cpp_hard.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
#include <iostream>
#include <vector>
// This chapter basically says why the meowing god on Earth my variable changes when passing through function
void pass_by_value(int x)
{
x += 1;
}
void pass_by_pointer(int *x)
{
(*x) += 1;
}
void pass_by_reference(int &x)
{
x += 1;
}
void swap_by_value(int a, int b) // this does not do swap
{
int temp = a;
a = b;
b = temp;
}
void swap_by_pointer(int *a, int *b) // not recommended in c++, but you will use it in the next semester
{
int temp = *a;
*a = *b;
*b = temp;
}
void swap_by_reference(int &a, int &b) // recommentded
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int x = 0;
int *x_address = &x;
int &x_reference = x;
// pass_by_value(x);
// pass_by_pointer(&x);
pass_by_reference(x);
std::cout << "value of x: " << x << "\n";
int a = 3, b = 5;
// swap_by_value(a, b);
// swap_by_pointer(&a, &b);
swap_by_reference(a, b);
std::cout << "a: " << a << "b: " << b << "\n";
}