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

Understanding 'Pass by Value'

Understanding 'Pass by Value'

What you'll learn: How C protects your original data by sending copies of variables to functions instead of the variables themselves.

The Photocopy Analogy

Imagine you have a piece of paper with a "5" written on it. Your friend asks to see it because they want to do some math. Instead of giving them your original paper, you walk over to a Xerox machine, make a perfect photocopy, and hand them the copy.

If your friend takes a red marker and crosses out the "5" on their paper to write a "10," what happens to your original paper in your pocket? Nothing. It still says "5."

In C, this is called Pass by Value. When you pass a variable into a function, the function receives a brand-new copy. Whatever the function does to that copy stays inside the function.

Seeing it in Code

Let's look at a function designed to "double" a number. Notice how the variable in main remains stubborn and unchanged.

#include <stdio.h>

void doubleNumber(int x) {
    x = x * 2; 
    printf("Inside function: x is %d\n", x);
}

int main() {
    int myNumber = 10;

    // We pass the value (10), not the variable itself
    doubleNumber(myNumber);

    printf("In main: myNumber is still %d\n", myNumber);
    return 0;
}

When you run this, the output shows that inside the function, x became 20. But back in main, myNumber is still 10.

Why does this happen?

When doubleNumber is called, C creates a new spot in the computer's memory specifically for the parameter x. It looks at myNumber, sees the value 10, and scribbles 10 into that new memory spot.

The two variables—myNumber and x—live in different "rooms" (scopes). They aren't connected by a tether; they are just two different buckets that happen to hold the same number for a brief moment. This is a safety feature: it prevents functions from accidentally messing up the data in your main program.

Key takeaway

In C, functions receive copies of your data, so modifying a parameter inside a function never changes the original variable you passed in.