Lesson 5 of 10
Values and references
- 12 min
- 5 checks
- 3 hints
- Go to task
Goal
Changing the original through a reference and passing a string without copying it
Explanation
When you call a function in C++, the function gets a copy of every value you pass to it, so void heal(int hp) { hp += 10; } increases its own copy, and the variable you passed stays exactly as it was. That's safe, but it isn't what you want when the function's job is to change the variable itself.
If you write & after the type, the parameter becomes a reference: another name for the very variable you passed, not a copy of it. So void heal(int& hp) { hp += 10; } changes the variable that was passed in. The call stays the same, heal(playerHp);, and the whole difference is in the function's signature, its first line. A reference needs a variable to refer to, so the compiler rejects heal(50): there's no variable there to change.
Copying a number costs next to nothing, but copying a long string or a big list is expensive, so const std::string& name passes the original without copying it, and const promises that the function won't change it: the compiler rejects any attempt to modify it. This is the usual way to pass strings and large objects that are only read, and you'll see it all over Unreal in the form const FString&.
Your task
The three functions are written, but they don't work, because each one modifies a copy. Run the program and look at the output, then fix their signatures so that swapValues(a, b) swaps the values of the variables themselves, addBonus(score, bonus) adds to the score itself and ignores a negative bonus, and addTag(name, tag) puts the tag in front of the name itself, as in [VIP] Layan, and reads tag as a constant reference, const std::string&.
Checks
5 checks- swapValues swaps the variables themselves
- addBonus adds to the score itself
- addBonus ignores a negative bonus
- addTag puts the tag in front of the name itself
- addTag reads tag as const std::string& with no copy