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 task
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.
Challenge 2
spend tries to change money, but it only changes its own copy. Rewrite it so it returns the money left, and so a purchase that costs more than you have changes nothing. Then store the result in main after each call. The program should print money 150.
Challenge 3
split tries to hand back two results through its parameters, which can't work because parameters are copies. Replace it with two functions, int minutes_of(int total) and int seconds_of(int total), that each return one result, and use them in main. Input 754 prints 12 min 34 sec.