📅 Date: Jan 8, 2026
🔥 Topic: Functions (Part 3): Pass by Value vs Reference
🤔 The Problem
Today I tried to write a function to swap two numbers. It seemed simple, but when I ran it, the numbers didn't swap in main().
This happened because of Pass by Value.
1️⃣ Pass by Value (The Photocopy)
When we pass variables normally, C++ creates a copy of that variable.
Result: Changes inside the function do NOT affect the original variable.
2️⃣ Pass by Reference (The Original)
To actually modify the original variable, we need to pass its Reference using the & symbol.
Result: The function gets access to the actual memory address of the variable.
💻 Day 8 Code: The Swap Test
Here is the code that finally worked using Pass by Reference.
#include <iostream>
using namespace std;
// Pass by Value (Won't work)
void fakeSwap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
// Pass by Reference (Works!)
// Notice the '&' symbol
void realSwap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
cout << "Original: " << x << " " << y << endl;
// Trying Fake Swap
fakeSwap(x, y);
cout << "After Fake Swap: " << x << " " << y << " (No Change)" << endl;
// Trying Real Swap
realSwap(x, y);
cout << "After Real Swap: " << x << " " << y << " (Swapped!)" << endl;
return 0;
}
💠Thoughts
The & operator is powerful. It allows functions to directly manipulate memory. It feels like giving someone the key to your house (Reference) vs giving them a photo of your house (Value).
No comments:
Post a Comment