C/C++ Arena

Step 2 of 10

Change the caller's variable

Remember that C passes arguments by value, so a function can't change your variables... unless you pass their address:

void damage(int *hp, int amount) {
    *hp -= amount;
}

int hp = 100;
damage(&hp, 30);   // hp is now 70

That's why scanf needs &x: it writes into your variable through a pointer.

Your turn: write void swap(int *a, int *b) that exchanges the two values.

Previous: Addresses and pointers Next: Returning two results