← C++ from Scratch Lesson 29 of 62 · 10 XP

Parameters: by value, by reference, by const reference

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

void byValue(int x)            { x = 0; }       // a copy: nothing changes outside
void byRef(int &x)             { x = 0; }       // a reference: we change the caller's variable
void show(const std::string &s) { std::cout << s; }   // const & — no copy and no right to change it
int power(int base, int exp = 2) { … }          // a default value: power(5) == 25

How to choose:

  • small types (int, double, char) — by value;
  • big ones (strings, vectors, structs) that don't need changing — const &: copying a string costs memory and time;
  • if you need to change the argument — & (or return a new value with return — that's usually clearer).

Task. Write void addXp(int &xp, int &level, int gained): it adds experience; every 100 experience points turn into +1 level (the remainder stays in xp). Read xp level, then the number of rewards k and k experience numbers; after each reward, print level xp.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.