Visualizing the stack frame copy
What you'll learn: How C protects your original data by creating isolated "photocopies" of variables inside a function’s own memory space.
The Office Cubicle Analogy
Imagine you are sitting at your desk (the main function) with a unique, handwritten document. Your boss (a different function) calls you and asks to see that document so they can make some edits.
In C, you don't hand over your original paper. Instead, you walk to the photocopier, make a duplicate, and hand the copy to your boss. Your boss takes that copy into their own office, scribbles all over it, and eventually throws it in the trash. When you look back at your desk, your original document is still perfectly clean.
This is "Pass by Value." The "Stack Frame" is like that private office; what happens inside the boss's office stays in the boss's office.
Seeing the Copy in Action
When you call a function, C carves out a new block of memory (a stack frame) for that function. It then copies the bits from your original variable into a new slot in that new frame.
#include <stdio.h>
void levelUp(int strength) {
strength = strength + 10;
// This 'strength' is a local copy.
// It exists only in levelUp's stack frame.
printf("Inside function: %d\n", strength);
}
int main() {
int heroStrength = 50;
levelUp(heroStrength);
// The original heroStrength remains untouched!
printf("In main: %d\n", heroStrength);
return 0;
}
Why the original doesn't change
When levelUp(heroStrength) is called, the value 50 is plucked out of main's memory and pasted into a new memory location labeled strength inside levelUp.
Think of the variable names as labels on different boxes. The strength box is in a different room than the heroStrength box. When the levelUp function adds 10, it is only reaching into its own box. Once the function finishes, its entire "office" (the stack frame) is demolished to save space. The original heroStrength in main was never even touched; it was just the source for the initial photocopy.
Key takeaway
In C, functions receive a copy of your data, ensuring the original variable in the calling function remains safe and unchanged.