2.8 — Changing types (casting)

📘 Chapter 2⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Automatic changes#

C++ sometimes changes a type for you. This is called a conversion.

C++
double d { 5 };     // the int 5 becomes 5.0int i = 3.9;        // the double 3.9 becomes 3 (decimals lost!)

static_cast: changing on purpose#

To change a type on purpose, use static_cast<new_type>(value).

C++
int apples { 7 };int people { 2 }; std::cout << apples / people << '\n';                       // 3std::cout << static_cast<double>(apples) / people << '\n';  // 3.5

char ↔ int#

C++
char c { 'B' };std::cout << static_cast<int>(c);   // 66 int n { 67 };std::cout << static_cast<char>(n);  // C
Key idea

static_cast says clearly: "I am changing this type on purpose." Readers (and the compiler) know it is not a mistake.

Turning text into numbers#

Text and numbers are different. "42" is not 42. To convert:

C++
int n { std::stoi("42") };              // string to intdouble d { std::stod("3.5") };          // string to doublestd::string s { std::to_string(99) };   // number to string
Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.