Local scope of parameters
What you'll learn: How function parameters act as private, temporary copies that don't affect variables in other parts of your program.
The Las Vegas Rule
In C, function parameters follow the "Las Vegas Rule": what happens inside the function, stays inside the function. When you pass a variable into a function, you aren't actually sending the variable itself. Instead, you are sending a photocopy of the value it holds.
This is known as local scope. Even if a parameter has the same name as a variable in main(), they are two completely different containers sitting in different rooms of your computer's memory.
An analogy: The Calculator
Imagine you have a notebook where you’ve written x = 10. You walk up to a friend who has a calculator. You don't give them your notebook; you just shout the number "10" to them.
Your friend types "10" into their calculator (the parameter), multiplies it by two to get 20, and then clears the screen. Back in your notebook, your x is still 10. Your friend’s actions changed their calculator's display, but they had no power to reach over and erase what was written in your notebook.
Seeing it in code
Notice how the variable num is treated in the example below:
#include <stdio.h>
void addFive(int num) {
num = num + 5;
printf("Inside function: %d\n", num);
}
int main() {
int num = 10;
// We pass a copy of 10 to the function
addFive(num);
// The original num remains unchanged
printf("Inside main: %d\n", num);
return 0;
}
When addFive(num) is called, the value 10 is copied into a new local variable also called num that belongs exclusively to the function. When the function adds 5, it updates its own copy to 15. As soon as the function reaches its closing curly brace, that copy is destroyed. When we return to main(), the original num is still 10.
Why this matters
This isolation is a feature, not a bug. It means you can write functions without worrying that you might accidentally overwrite important data elsewhere in your program. Each function is its own little island, keeping its data safe and private.
Key takeaway
Function parameters are local copies; changing a parameter's value inside a function never changes the original variable passed to it.