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

Limitations of pass by value

Limitations of pass by value

What you'll learn: Understand why standard C functions cannot modify the original variables passed into them.

The Photocopy Analogy

Imagine you have a master sheet of paper with a number written on it. You want your friend to perform a calculation on that number, so you hand them a photocopy. Your friend scribbles on their copy, crosses out the number, and writes a new one. When they finish, they throw their paper away.

Back at your desk, your master sheet remains completely unchanged. This is exactly how C handles arguments by default. It doesn't give the function your "original" variable; it gives the function a temporary copy.

The "Local" Trap

When you pass a variable to a function, the function creates a new, local variable to hold that value. Any changes made inside that function happen to the copy, not the source. Once the function reaches its closing curly brace, that copy is deleted from the computer's memory.

Look at this attempt to update a player's score:

#include <stdio.h>

void updateScore(int score) {
    score = score + 100;
    printf("Inside function, score is: %d\n", score);
}

int main() {
    int myScore = 50;
    
    updateScore(myScore);
    
    printf("In main, myScore is still: %d\n", myScore);
    return 0;
}

When you run this, the function will proudly announce the score is 150. But back in main, the score is still 50. The updateScore function was just playing with a clone.

Why does this limitation exist?

It might seem frustrating, but "pass by value" is actually a safety feature. It prevents functions from accidentally overwriting data in other parts of your program. It keeps the "scope" of your variables isolated.

However, the limitation is clear: if you need a function to change a variable permanently—like updating a player's health or sorting a list—pass by value cannot do it alone. You are restricted to only getting information back via the return statement, which can only send back one single piece of data. To overcome this and modify the original variable directly, C programmers eventually have to use a different tool: Pointers.

Key takeaway

Pass by value protects your original data, but it means a function can never modify the variables you pass into it.