Lesson 5 of 10

Values and references

Goal

Changing the original through a reference and passing a string without copying it

01

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&.

02

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
  1. swapValues swaps the variables themselves
  2. addBonus adds to the score itself
  3. addBonus ignores a negative bonus
  4. addTag puts the tag in front of the name itself
  5. addTag reads tag as const std::string& with no copy
03

Hints

0/3
Track lessons0 of 10 done

C++ is the language behind game engines, browsers and operating systems, because it's fast and gives you full control.

Beginner level, 10 lessons, 2 hours in total.

main.cpp
OutputC++17 (GCC 9, Judge0)

Compiling and running your code on the server.

–/5

Compiling and running your code on the server.

5 checks listed under “Your task”.

Track lessons0 of 10 done

C++ is the language behind game engines, browsers and operating systems, because it's fast and gives you full control.

Beginner level, 10 lessons, 2 hours in total.