C/C++ Arena

Step 5 of 7

Scope and pass by value

Variables declared inside a function only exist inside it (local scope).

C passes arguments by value: the function gets a copy. Changing the parameter doesn't change the caller's variable:

void reset(int hp) { hp = 100; }   // changes the copy only

int hp = 20;
reset(hp);
printf("%d\n", hp);   // still 20

(To change the caller's variable you need pointers, coming soon.)

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