Preparing for pass by reference
What you'll learn: Why C functions work with copies of data and why this prevents them from changing original variables.
The Photocopy Analogy
Imagine you have a piece of paper with the number "10" written on it. You want your friend to double that number. In C, when you pass a variable to a function, it is like walking over to a photocopy machine, making a copy of your paper, and handing your friend the copy.
Your friend takes their copy, scribbles out the 10, and writes "20." They are very happy with their work! However, when you look at the original paper still sitting in your pocket, it still says "10." Your friend changed their copy, but they never touched your original. This is called Pass by Value.
Seeing the Copy in Action
In C, every function has its own private workspace (called a "stack frame"). When you pass a variable into a function, C creates a brand-new variable in that workspace and fills it with the same value.
Look at how the increment function fails to change the original score:
#include <stdio.h>
void increment(int score) {
score = score + 1;
printf("Inside function: %d\n", score); // Prints 11
}
int main() {
int myScore = 10;
increment(myScore);
printf("In main: %d\n", myScore); // Still prints 10!
return 0;
}
The "One-Way Street" Limitation
When main calls increment(myScore), the value 10 is plucked out and dropped into the function's local score variable. At that moment, the link between myScore and score is broken. They are two different boxes in your computer's memory that just happen to hold the same number for a split second.
This is actually a safety feature! It ensures that functions don't accidentally mess up your data. However, as you build more complex programs, you will eventually want a function to reach back into your pocket and change the original paper. To do that, we can't just give the function a photocopy; we have to give it a map to our house.
Understanding that functions currently only work with copies is the essential first step toward mastering pointers, which act as those maps.
Key takeaway
By default, C functions receive copies of data, meaning any changes made inside the function disappear the moment the function ends.