Codiqo

Learn C++ · lesson 8 of 61 · about 7 minutes

auto, const and Conversions

Show the hero's health as HP 85/100: lock values with const, let the compiler infer types with auto, and convert between numbers and text.

What you'll learn

  • Use auto
  • Use const for fixed values
  • Convert with static_cast, std::stoi and std::to_string

A health label

The game should show the hero's health as *HP 85/100*. The 100 is the most health anyone can have, and it should never change, so the compiler should stop anyone changing it. And to glue numbers into a std::string, they have to be turned into text first.

auto and const

  • const int MAX_HEALTH = 100; can't be changed after it's set, and the compiler enforces it
  • auto potions = 2; lets the compiler work out the type (here int) from the value

Use const for anything that shouldn't change, and auto when the type is obvious or long to write.

Converting

| Want | Use | Example |
|---|---|---|
| number → text | std::to_string(n) | 85 → "85" |
| text → int | std::stoi(s) | "42" → 42 |
| text → double | std::stod(s) | "2.5" → 2.5 |
| int → double | static_cast<double>(x) | 7 → 7.0 |
| double → int | static_cast<int>(d) | 3.99 → 3 |

The label, and three more conversions

#include <iostream>
#include <string>

int main() {
    const int MAX_HEALTH = 100;
    int health = 85;
    auto potions = 2;
    std::string label = "HP " + std::to_string(health) + "/" + std::to_string(MAX_HEALTH);
    std::cout << label << "\n";
    std::cout << health / potions << " " << static_cast<double>(health) / potions << "\n";
    std::cout << std::stoi("42") + 1 << "\n";
    std::cout << static_cast<int>(3.99) << "\n";
}

Output

HP 85/100
42 42.5
43
3

Tip

std::stoi only works on text that starts with a number. std::stoi("ten") stops the program with std::invalid_argument.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.