Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 171 ยท Variables and Types

Type Conversions and Casts

Learn how C++ converts types implicitly (promotions, arithmetic conversions), how brace init stops narrowing, how to use static_cast, and why C-style casts are risky.

C++ converts values between types all the time, often without telling you. Add an int to a double and the int becomes a double. Store a double in an int and the fraction disappears. Compare a negative int with an unsigned value and the negative number turns into four billion. Most of these implicit conversions are helpful, but a handful cause the most common numeric bugs in C++.

When you want a conversion, you write a cast, and modern C++ gives you four named ones, each for a specific job. This lesson explains the rules the compiler follows on its own, how brace initialization protects you from losing data, how to convert on purpose with static_cast, and why the old C-style cast (int)x is best avoided.

Implicit conversions

An implicit conversion happens whenever a value of one type is used where another type is expected: in an initialization or assignment, as a function argument, in a return, or as an operand of an arithmetic operator.

C++
double d = 7;            // int 7 converted to double 7.0
int i = 3.99;            // double converted to int: 3 (the fraction is cut off)
bool b = 42;             // nonzero converted to true
long long big = i;       // int widened to long long
float f = 0.1;           // double converted to float: loses precision

Some of these are widening (every value of the source fits in the target, like int โ†’ long long or float โ†’ double) and are completely safe. Others are narrowing: the target can't represent every source value, so information may be lost. double โ†’ int drops the fraction, int โ†’ char keeps only the low byte, and a large long long โ†’ float loses digits.

The surprising part is that narrowing with = compiles silently, even with -Wall -Wextra. GCC and Clang can warn about it with the extra flag -Wconversion, which many teams enable, but it is not on by default.

Integral promotion: small types become int

Arithmetic in C++ never happens on types smaller than int. Before an arithmetic operator runs, values of type bool, char, signed char, unsigned char, short and unsigned short are promoted to int (or to unsigned int in the rare case that int can't hold all their values). This is why adding two chars gives an int:

C++ Promotions in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Promotion is usually helpful: level + bonus computes 300 correctly instead of wrapping inside 8 bits. The wrap happens only when you store the int result back into a uint8_t (300 โˆ’ 256 = 44). Keep it in mind whenever you work with small integer types.

The usual arithmetic conversions

When a binary operator like +, * or < has operands of different arithmetic types, the compiler converts them to a common type first. Simplified, the rules are:

  1. If either operand is a floating-point type, the other is converted to the largest floating-point type involved: int + double โ†’ double, float + double โ†’ double.
  2. Otherwise both are promoted (see above), and then the operand with the smaller rank (roughly: fewer bits) is converted to the type of the other: int + long long โ†’ long long.
  3. If they have the same size but different signedness, the signed one is converted to unsigned: int + unsigned int โ†’ unsigned int. This is the trap from Integer Types.
C++ Common types in expressions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

double too_late = items / boxes; is one of the most frequent beginner bugs: the right side is evaluated first, entirely in int, and gives 3. Only then is 3 converted to 3.0. To get 3.5, at least one operand must already be floating point when the division happens.

Floating-point to integer conversion

Converting a floating-point value to an integer type truncates toward zero: 3.99 becomes 3, and โˆ’3.99 becomes โˆ’3. It does not round. If you want rounding, say so with <cmath>:

C++ Truncating vs rounding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

std::lround and std::llround return long and long long; std::round, std::floor and std::ceil return a floating-point value that you can then convert. Math Functions covers them in detail.

Out-of-range floating-point to integer conversion is undefined behavior. static_cast<int>(1e10), or converting NaN or infinity to any integer type, has no defined result. On x86 you often get โˆ’2147483648, but compilers may also produce something else. Check the range first when the value comes from outside your program.

Brace initialization blocks narrowing

Initializing with braces {} (introduced in Variables) has one big advantage: the standard says a narrowing conversion inside braces makes the program ill-formed, so the compiler must diagnose it.

C++
double price = 9.99;

int a = price;          // compiles: a is 9, silently
int b(price);           // compiles: b is 9, silently
int c{price};           // diagnosed: narrowing conversion of 'price' from 'double' to 'int'
int d{static_cast<int>(price)};   // fine: you said you meant it

char e{300};            // error: 300 doesn't fit in char
unsigned f{-1};         // error: negative value to unsigned
int g{7};               // fine
double h{7};            // fine: the constant 7 fits exactly

For constants, the compiler checks whether the actual value fits: char e{65}; is allowed because 65 fits, while char e{300}; and unsigned f{-1}; are hard errors. For variables, every potentially lossy conversion is diagnosed, but compilers differ in how. Clang and MSVC reject int c{price}; with an error. GCC, for compatibility with older code, only reports a warning for non-constant values and then compiles the program anyway. Run this on our GCC server to see it:

C++ Narrowing in braces is diagnosed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

GCC prints warning: narrowing conversion of 'average_score' from 'double' to 'int' [-Wnarrowing] and the program prints 87. With Clang or MSVC the same code doesn't compile. Many projects add -Werror=narrowing (or -Werror for all warnings) so GCC treats it as the error the standard intends. Either way, replace the initializer with static_cast<int>(average_score) (or better, std::lround(average_score)) and the diagnostic goes away. This protection is a strong reason to prefer brace initialization when converting values.

static_cast: converting on purpose

static_cast<Type>(expression) is the everyday tool for explicit conversions. Use it to:

  • convert between arithmetic types: static_cast<double>(count), static_cast<int>(3.7)
  • convert between signed and unsigned: static_cast<std::size_t>(index)
  • convert integers to and from enum types
  • convert pointers up and down a class hierarchy (when you already know the real type)
  • convert to and from void*

It is checked by the compiler: static_cast refuses conversions that make no sense, such as turning a double* into an int*, or removing const.

C++ static_cast for clear intent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

A cast is also documentation. static_cast<int>(average / 5.0 * 100.0) tells every reader "yes, I know this drops the fraction." That is exactly why named casts are long and slightly ugly: conversions that lose information deserve to stand out.

The C-style cast problem

C++ still accepts the cast syntax inherited from C, plus a "functional" form:

C++
double ratio = 0.75;
int a = (int)ratio;    // C-style cast
int b = int(ratio);    // functional cast: same meaning for a single value

For simple numeric conversions these do the same as static_cast. The problem is that a C-style cast will silently do whatever it takes: it tries const_cast, static_cast, reinterpret_cast and combinations of them until something compiles. One innocent-looking set of parentheses can strip const or reinterpret memory as a completely unrelated type:

C++ What a C-style cast can hide

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Neither cast produces an error or a warning. The first strips const; the second turns a double* into a long long*, and reading a double through that pointer breaks C++'s aliasing rules (undefined behavior that optimizers really do exploit). With named casts, each would have needed an explicit, searchable const_cast or reinterpret_cast. To inspect the bits of a value correctly, use std::bit_cast from <bit> (C++20), as the last line does.

Use named casts in C++ code. They say what kind of conversion you mean, the compiler rejects the wrong kind, and you can search a codebase for reinterpret_cast or const_cast to review every dangerous spot. Many style guides and the -Wold-style-cast warning enforce this.

The other three named casts

You'll meet these properly later. For now, know what each one is for:

Cast Purpose How often
static_cast<T>(x) normal, compiler-checked conversions constantly
const_cast<T>(x) add or remove const (and volatile) rarely; mainly to call old APIs that forgot const. Modifying an object that was defined const is undefined behavior
reinterpret_cast<T>(x) reinterpret a pointer or reference as an unrelated type, or a pointer as an integer rarely; low-level code (hardware, serialization). Very easy to get wrong
dynamic_cast<T>(x) safely convert a base-class pointer/reference to a derived class, checked at run time occasionally; see RTTI, dynamic_cast and typeid
C++
void legacy_log(char* message);            // an old API that should take const char*

const char* text = "started";
legacy_log(const_cast<char*>(text));       // OK only if legacy_log never writes to it

std::uint32_t value = 0x11223344;
auto* bytes = reinterpret_cast<const unsigned char*>(&value);   // viewing bytes is allowed

Shape* shape = get_shape();
if (auto* circle = dynamic_cast<Circle*>(shape)) {   // nullptr if it isn't a Circle
    circle->set_radius(2.0);
}

If you find yourself reaching for const_cast or reinterpret_cast in ordinary application code, it usually means a design problem upstream.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int a = 9, b = 2; double r = a / b; What is r?

    a / b is computed in int first (integer division gives 4), and only the result is converted to double, 4.0. Write static_cast<double>(a) / b to get 4.5.
  2. 2. What is static_cast<int>(-7.8)?

    Floating-point to integer conversion truncates toward zero, so -7.8 becomes -7. Use std::lround for rounding (-8).
  3. 3. Which line does the C++ standard treat as an ill-formed narrowing conversion?

    Narrowing inside braces, such as double to int, is ill-formed and must be diagnosed (an error in Clang and MSVC, a warning by default in GCC). The other forms convert silently or explicitly.
  4. 4. char a = 100, b = 100; auto c = a + b; What is the type and value of c?

    Both chars are promoted to int before the addition, so c is an int holding 200.
  5. 5. Why are C-style casts like (T)x discouraged in C++?

    A C-style cast tries const_cast, static_cast and reinterpret_cast combinations until one works, hiding dangerous conversions. Named casts state the intent and are checked.

Summary

  • Implicit conversions happen in initialization, assignment, function calls, returns and mixed expressions. Widening is safe; narrowing (like double โ†’ int) can lose data and compiles silently with =.
  • Types smaller than int are promoted to int before arithmetic, so char + char is an int.
  • In mixed expressions, integers convert to floating point, smaller types convert to larger ones, and signed converts to unsigned when sizes match.
  • Convert before dividing: static_cast<double>(sum) / count. Floating-to-integer conversion truncates toward zero; out-of-range values are undefined behavior.
  • Brace initialization (int n{x};) makes narrowing a compiler diagnostic: an error for constants, and for variables an error in Clang/MSVC and a warning in GCC (use -Werror=narrowing).
  • Use static_cast for intentional conversions. Avoid C-style casts; const_cast, reinterpret_cast and dynamic_cast exist for rare, specific jobs.

Next: Type Aliases: using and typedef, where you'll give long or meaningful names to types.