Pass-by-value limitations
What you'll learn: Why functions in C cannot naturally modify variables from your main code and how this creates a "one-way street" for data.
The Photocopy Analogy
Imagine you have a physical piece of paper with a number written on it. You want your friend to double that number. Instead of giving them your original paper, you take a photocopy and hand that to them.
Your friend scribbles on the photocopy, changes the number, and throws it away. When you look at the original paper still in your hand, the number hasn't changed. This is exactly how Pass-by-value works in C. When you pass a variable to a function, C makes a "photocopy" (a local copy) of the data. The function works on that copy, and when the function ends, the copy is destroyed. The original variable remains untouched.
Seeing the Limitation in Code
In the example below, we try to create a function that increments a player's score. Even though the function adds 10 to the variable it receives, the change doesn't "stick" to the original variable.
#include <stdio.h>
void addScore(int localScore) {
localScore = localScore + 10;
printf("Inside function: %d\n", localScore);
}
int main() {
int myScore = 50;
addScore(myScore);
printf("In main: %d\n", myScore);
// Output will still be 50!
return 0;
}
Why This Happens
When addScore(myScore) is called, C looks at the value inside myScore (which is 50) and copies that number into a brand new memory bucket named localScore.
The addScore function is only aware of its own bucket. It successfully changes 50 to 60 inside localScore, but it has no connection back to myScore. Once the function hits the closing curly brace, the localScore bucket is erased from memory. The original myScore in main was never even invited to the party.
This is a major limitation: if you want a function to update a variable, perform a swap, or modify a large structure, Pass-by-value simply cannot do it. To break through this limitation, we need a way to give the function the "original paper" rather than a photocopy.
Key takeaway
Pass-by-value only gives functions a copy of your data, meaning any changes made inside the function are lost forever once the function finishes.