C/C++ Arena

Step 5 of 7

Scope and pass by value

Scope: where a name exists

A variable declared inside a function is local to it. It's created when the function starts and destroyed when it returns, and no other function can see it. Two functions can each have their own variable named total and they never interfere. The same goes for variables declared inside any { } block, like a loop body.

Pass by value

When you call a function, C copies each argument's value into the matching parameter. The function works on its own copy:

#include <stdio.h>

void try_to_double(int n) {
    n = n * 2;
    printf("inside: %d\n", n);
}

int doubled(int n) {
    return n * 2;
}

int main(void) {
    int score = 10;
    try_to_double(score);
    printf("after try: %d\n", score);
    score = doubled(score);
    printf("after return: %d\n", score);
    return 0;
}
inside: 20
after try: 10
after return: 20

try_to_double doubled its copy, which vanished when it returned. main's score was never touched. doubled does the right thing: it returns the new value, and main stores it.

Why C works this way

Copying keeps functions independent: calling a function can't secretly change your variables, which makes programs easier to reason about. When a function really does need to change the caller's variable, there are two ways: return the new value (best when there's one result), or pass the variable's address with a pointer, which is coming up in the pointers module.

Your turn: heal below tries to modify its parameter. Rewrite it to return the new value instead, and store that result in main so the program prints hp 75.

Previous: Prototypes Next: Recursion