-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreferences.cpp
More file actions
54 lines (40 loc) · 1.98 KB
/
Copy pathreferences.cpp
File metadata and controls
54 lines (40 loc) · 1.98 KB
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
#include <iostream>
#include <string>
using namespace std;
int main() {
// ===================================================
// 1. CREATING REFERENCES
// ===================================================
// A reference variable is an ALIAS (another name) for an existing variable.
// Created using the `&` operator.
string food = "Pizza"; // Original variable
string &meal = food; // Reference (alias) to food
cout << "=== 1. CREATING REFERENCES ===" << endl;
cout << "Food: " << food << endl; // Output: Pizza
cout << "Meal: " << meal << endl; // Output: Pizza
// ===================================================
// 2. UPDATING THROUGH REFERENCES
// ===================================================
// Since food and meal refer to the EXACT SAME memory location,
// changing one will also change the original variable.
cout << "\n=== 2. UPDATING THROUGH REFERENCES ===" << endl;
meal = "Burger"; // Modifying value via reference
cout << "Food: " << food << endl; // Output: Burger
cout << "Meal: " << meal << endl; // Output: Burger
// ===================================================
// 3. MEMORY ADDRESS
// ===================================================
// The `&` operator is also used to retrieve a variable's memory address (in Hexadecimal format, e.g., 0x6dfed4).
cout << "\n=== 3. MEMORY ADDRESS ===" << endl;
cout << "Memory Address of food: " << &food << endl;
cout << "Memory Address of meal: " << &meal << endl; // Address is EXACTLY THE SAME as &food!
// ===================================================
// KEY TAKEAWAYS:
// ===================================================
/*
1. A reference does NOT allocate new memory; it simply creates an alias name.
2. References and Pointers are crucial in C++ for manipulating data directly
in computer memory, which optimizes memory usage & boosts program performance.
*/
return 0;
}