Skip to content

Commit 1862076

Browse files
committed
Add References in C++
1 parent 4dcb328 commit 1862076

File tree

2 files changed

+17
-28
lines changed

2 files changed

+17
-28
lines changed

HelloWorld/enc_temp_folder/da161bb8f251f3ed50cc60fc5881cf20/Main.cpp

Lines changed: 0 additions & 19 deletions
This file was deleted.

HelloWorld/src/Main.cpp

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,26 @@
22

33
#define LOG(x) std::cout << x << std::endl
44

5+
void Increment(int* value) // use pointer to get the memory address of the variable passed by as parameter so we can modify it.
6+
{
7+
(*value)++; // dereference the value so that we can actually write to that memory instead of modifying the pointer itself
8+
}
9+
10+
void Increment(int& value) // pass by references, exactly the same thing as above but clearer
11+
{
12+
value++;
13+
}
14+
515
int main()
616
{
7-
int var = 8;
8-
int* ptr = &var;
9-
*ptr = 10;
10-
LOG(var);
17+
int a = 5;
18+
int& ref = a; // ref is a, Reference is just creating an allias of a to be used as if it was a.
19+
ref = 2;
1120

12-
char* buffer = new char[8]; // => 8 bytes of memory, return a pointer to the beginning of that block of memory
13-
memset(buffer, 0, 8);
21+
LOG(a);
1422

15-
char** cptr = &buffer; // => &buffer means get the memory address reference of the integer (pointer) that referenced a 8 bytes of char data
23+
Increment(a); // use ampersand to get the memory address reference of that variable
24+
LOG(a);
1625

17-
delete[] buffer;
18-
std::cin.get(); // ==> Dead Code
26+
std::cin.get();
1927
}

0 commit comments

Comments
 (0)