Course contentsShow
← C
Lesson 343 of 1,2195. FunctionsFree lesson

Why changing a parameter doesn't affect the caller

Why changing a parameter doesn't affect the caller

What you'll learn: Why functions work on local copies of data rather than the original variables you pass to them.

The Photocopy Analogy

Imagine you have a piece of paper with the number 10 written on it. You want your friend to perform a calculation with that number, so you hand them a photocopy of your paper.

Your friend takes their photocopy, scribbles out the 10, and writes 20 instead. Does the number on the paper sitting in your hand change? Of course not. Your friend only altered their copy.

In C, this behavior is called Pass by Value. When you pass a variable into a function, the computer doesn't give the function the actual variable; it gives the function a brand-new copy of the data stored inside that variable.

Seeing the Copy in Action

Let's look at a function that tries to "update" a score. Because C passes by value, the function creates a local variable (the parameter) that exists only inside the curly braces.

#include <stdio.h>

void becomeRich(int money) {
    money = money + 1000;
    printf("Inside function: %d\n", money);
}

int main() {
    int mySavings = 50;
    
    // We pass the VALUE of mySavings (50) to the function
    becomeRich(mySavings);
    
    // Back in main, mySavings is still 50
    printf("Outside function: %d\n", mySavings);
    
    return 0;
}

When becomeRich(mySavings) is called, the value 50 is copied into the parameter money. Inside the function, money becomes 1050. However, money and mySavings are two completely different spots in the computer's memory. Once the function finishes, the money variable is destroyed, and mySavings remains exactly as it was.

Why C Works This Way

This might seem frustrating at first, but it is actually a safety feature. It prevents a function from accidentally messing up the data in other parts of your program. It ensures that what happens inside a function stays inside that function, unless you explicitly choose to return a value or use more advanced techniques like pointers.

Key takeaway

In C, functions receive a copy of your data, so any changes made to a parameter stay inside that function and never affect the original variable.