Pass-by-Value vs Pass-by-Reference
What you'll learn: How functions receive data differently—either as independent copies or as direct access to the original variable.
When you call a function with arguments, the computer must decide how to transfer that data. There are two fundamental approaches:
Pass-by-Value
In pass-by-value, the function receives a copy of the original data. Any changes the function makes affect only this copy, leaving the original variable untouched.
Think of it like photocopying a document: you hand someone the copy to edit. Whatever they write on it doesn't affect your original.
void increment(int num) {
num = num + 1; // Changes the copy only
}
int main() {
int x = 5;
increment(x);
// x is still 5 — the original wasn't modified
}
Pass-by-Reference
In pass-by-reference, the function receives the memory address (a pointer) to the original variable. Now the function can directly modify the original data by dereferencing that address.
This is like giving someone your actual document with your home address written on it. They can visit your house and modify the original.
void increment(int *numPtr) {
*numPtr = *numPtr + 1; // Dereferences to modify original
}
int main() {
int x = 5;
increment(&x); // Pass address of x
// x is now 6 — original was modified
}
Why Does This Matter?
Pass-by-value is safer (no accidental modifications) but creates copies. Pass-by-reference enables functions to modify caller variables and avoids copying large data structures.
Key Takeaway: Pass-by-value gives functions independent copies; pass-by-reference (using pointers) gives functions the ability to modify the original variable by working with its memory address.