Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Quiz: Copy or Reference?

What does this program print?

1#include <iostream>
2#include <string>
3#include <vector>
4
5struct Monster {
6    std::string name;
7    int health;
8};
9
10int main() {
11    std::vector<Monster> monsters = {{"Goblin", 30}, {"Orc", 50}};
12
13    for (Monster monster : monsters) {
14        monster.health -= 10;
15    }
16    for (Monster& monster : monsters) {
17        monster.health -= 5;
18    }
19    Monster first = monsters[0];
20    first.health = 0;
21
22    std::cout << monsters[0].health << " " << monsters[1].health << std::endl;
23    return 0;
24}
Back

6/12

  1. 1. What Is a Struct?
  2. 2. Braces and Default Values
  3. 3. Copies and References
  4. 4. A Vector of Structs
  5. 5. Changing Structs in a Loop
  6. 6. Quiz: Copy or Reference?
  7. 7. Structs and Functions
  8. 8. Returning a Struct
  9. 9. Structs Inside Structs
  10. 10. Enumerations: enum class
  11. 11. Quiz: Rarity Names
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.