Chapter 08 of 48

Type Conversion & Casting

On this page

In the Operators chapter we saw that 17 / 5 gives 3 but 17.0 / 5 gives 3.4. The only difference was the type of one operand. Whenever values of different types meet in an expression, an assignment, or a function call, C++ has to convert at least one of them. Sometimes it does this automatically; sometimes we must ask for it ourselves.

Getting conversions wrong causes some of the most famous C++ bugs: averages that lose their decimals, -1 that turns out to be "greater" than 1, and values that silently get chopped. In this chapter we will learn the exact rules, and then the four C++ cast operators that let us convert on purpose.


What is Type Conversion?

Type conversion is the process of producing a value of one type from a value of another type. If the compiler does it automatically, it is an implicit conversion. If the programmer requests it with a cast, it is an explicit conversion (type casting).

Implicit:  double d = 7;                      // compiler converts 7 → 7.0
Explicit:  int i = static_cast<int>(7.8);     // we ask for 7.8 → 7

The value may or may not survive the trip. Converting 7 to 7.0 is exact. Converting 7.8 to int loses the fraction. A conversion that may lose information is called a narrowing conversion; one that never loses information is a widening (or safe) conversion.


Implicit Conversions in Assignment and Initialisation

When you store a value into a variable of a different type, the value is converted to the variable's type.

#include <iostream>

int main() {
    int count = 7;
    double d = count;          // int → double: exact
    int truncated = 9.99;      // double → int: fraction is dropped
    int code = 'A';            // char → int
    bool flag = 42;            // non-zero → true
    int fromBool = true;       // true → 1

    std::cout << d << ' ' << truncated << ' ' << code << ' '
              << flag << ' ' << fromBool << '\n';

    float f = 16777217;        // int → float: precision lost
    std::cout.precision(10);
    std::cout << f << '\n';
    return 0;
}

Output:

7 9 65 1 1
16777216

Observations:

  • 9.99 became 9, not 10. Floating → integer conversion truncates toward zero; it never rounds. (Use std::round from <cmath> if you want rounding.)
  • Any non-zero number converts to true; zero converts to false. true converts to 1 and false to 0.
  • 16777217 (224 + 1) cannot be stored exactly in a float, which has only 24 bits of precision, so the nearest representable value 16777216 is stored. Integer → floating conversion can lose precision even when the range is fine.

Notice that the compiler accepted int truncated = 9.99; without a word, even with -Wall -Wextra. Adding -Wconversion makes GCC warn about such value-changing conversions; it is a very useful flag for beginners.


Integral Promotion

Integral promotion: before arithmetic, small integer types (bool, char, signed char, unsigned char, short, unsigned short) are converted to int (or to unsigned int if int cannot hold all their values).

The CPU works most naturally with int-sized values, so C++ never does arithmetic directly on a char or short.

#include <iostream>

int main() {
    char a = 'A', b = 'B';
    short s = 1000;
    std::cout << a + b << '\n';              // char + char → int
    std::cout << sizeof(a) << ' ' << sizeof(a + b) << '\n';
    std::cout << s * s << '\n';              // short * short → int, no overflow
    std::cout << '7' - '0' << '\n';          // digit character → number
    char next = a + 1;                       // int result converted back to char
    std::cout << next << '\n';
    return 0;
}

Output (with a 4-byte int):

131
1 4
1000000
7
B
  • a + b prints 131 (65 + 66), not a character, because the result is an int. This surprises many beginners.
  • s * s is 1,000,000, which does not fit in a 16-bit short, but there is no problem because the multiplication happens in int.
  • '7' - '0' is 7 because digit characters have consecutive codes. This trick converts a digit character to its numeric value and is used everywhere in parsing and competitive programming.

Usual Arithmetic Conversions

When a binary operator like +, -, *, /, < or == gets two operands of different arithmetic types, C++ brings both to a common type using these rules, in order:

  1. If either operand is long double, the other is converted to long double. Otherwise, if either is double, the other becomes double. Otherwise, if either is float, the other becomes float.
  2. Otherwise, both are integers. First apply integral promotion to both.
  3. If they now have the same type, done. If both are signed, or both unsigned, the one with the smaller rank is converted to the larger one (int → long → long long).
  4. If the unsigned operand's rank is greater than or equal to the signed one's, the signed operand is converted to unsigned.
  5. Otherwise, if the signed type can represent all values of the unsigned type, the unsigned operand is converted to the signed type; if not, both are converted to the unsigned version of the signed type.

A simplified picture for everyday code:

int → long → long long → float → double → long double
(and: same rank, signed meets unsigned → unsigned wins)

Worked Example: The Average Bug

#include <iostream>

int main() {
    int total = 425, subjects = 6;

    double wrong = total / subjects;                        // int / int first!
    double right = static_cast<double>(total) / subjects;   // double / int

    std::cout << "wrong = " << wrong << '\n';
    std::cout << "right = " << right << '\n';

    long long big = 2'000'000'000;
    int n = 2;
    std::cout << big * n << '\n';     // int converted to long long
    std::cout << 5 / 2 * 2.0 << ' ' << 5 / 2.0 * 2 << '\n';
    return 0;
}

Output:

wrong = 70
right = 70.8333
4000000000
4 5

Step by step:

wrong: total / subjects  → int / int → 70 (fraction lost)
       70 → converted to double → 70.0 (too late!)

right: static_cast<double>(total) → 425.0
       425.0 / subjects → double / int → int converted to double
       425.0 / 6.0 → 70.8333...

5 / 2 * 2.0   → (5 / 2) * 2.0 → 2 * 2.0 → 4.0
5 / 2.0 * 2   → 2.5 * 2       → 5.0

The lesson: the type of an expression is decided by its operands, not by the variable you store the result in. Convert one operand before the division.


The Signed/Unsigned Trap

#include <iostream>
#include <utility>   // std::cmp_less (C++20)

int main() {
    int a = -1;
    unsigned int b = 1;
    std::cout << std::boolalpha;
    std::cout << (a < b) << '\n';                  // -1 converted to unsigned!
    std::cout << static_cast<unsigned int>(a) << '\n';
    std::cout << std::cmp_less(a, b) << '\n';      // mathematically correct

    unsigned int items = 3, removed = 5;
    std::cout << items - removed << '\n';          // wraps around
    return 0;
}

Output:

false
4294967295
true
4294967294

-1 < 1 is false! By rule 4 above, int and unsigned int have the same rank, so -1 is converted to unsigned int. Conversion to an unsigned type is done modulo 2N, so -1 becomes 232 − 1 = 4294967295, which is certainly not less than 1. Likewise, 3u - 5u cannot be negative, so it wraps to 232 − 2.

GCC catches the comparison with -Wall:

warning: comparison of integer expressions of different signedness: ‘int’ and ‘unsigned int’ [-Wsign-compare]

Fixes: avoid mixing signed and unsigned values, or use the C++20 safe comparison functions std::cmp_equal, std::cmp_less, std::cmp_greater and friends from <utility>, which compare the true mathematical values. This trap is common with container sizes, which are unsigned; you will meet it again in the vector chapter.


What Happens When the Value Does Not Fit?

This table is worth memorising for exams and interviews:

ConversionIf the value fitsIf it does not fit
Any integer → unsigned integerUnchangedWell-defined: reduced modulo 2N
Any integer → signed integerUnchangedSince C++20: modulo 2N (two's complement). Before C++20: implementation-defined
Floating → integerFraction truncated toward zeroUndefined behavior (if the truncated value is out of range)
Integer → floatingExactOne of the two nearest representable values (precision lost); UB only if outside the floating type's whole range
double → floatRounded to float precisionUndefined behavior if outside float's range
Anything → bool0 (or null pointer) → false; anything else → trueNot applicable: every value converts
#include <iostream>

int main() {
    int big = 300;
    unsigned char uc = big;                       // 300 mod 256 = 44
    signed char sc = static_cast<signed char>(200); // 200 - 256 = -56 (defined since C++20)
    unsigned int u = -1;                          // -1 mod 2^32
    int fromNeg = static_cast<int>(-3.99);        // truncates toward zero

    std::cout << static_cast<int>(uc) << ' ' << static_cast<int>(sc) << '\n';
    std::cout << u << ' ' << fromNeg << '\n';
    return 0;
}

Output:

44 -56
4294967295 -3

We printed uc and sc through static_cast<int> because cout prints char types as characters, not numbers. Note that -3.99 becomes -3 (toward zero), not -4.


Brace Initialisation Stops Narrowing (C++11)

C++11 introduced list initialisation with braces {}. One of its big advantages: narrowing conversions inside braces are not allowed.

int main() {
    double price = 99.99;
    int a = price;      // compiles: silent narrowing
    int b(price);       // compiles: silent narrowing
    int c{price};       // error: narrowing inside braces
    return a + b + c;
}

The standard says int c{price}; is ill-formed. Clang and MSVC reject it with an error. GCC is a little lenient here: for a non-constant value it only gives a warning by default:

warning: narrowing conversion of ‘price’ from ‘double’ to ‘int’ [-Wnarrowing]

With -pedantic-errors (or -Werror=narrowing), GCC turns this into an error, and for constants such as int c{99.99}; or char d{300}; GCC always reports an error. Prefer brace initialisation in new code so the compiler can catch accidental narrowing for you.


Explicit Conversion: Type Casting

Sometimes we want a conversion: to force real division, to turn a double into an index, or to see the numeric code of a character. C++ gives us several ways to ask.

CastPurposeChecked when?
static_cast<T>(x)Ordinary, well-understood conversions (numeric types, enum, void*, up/down a class hierarchy without a run-time check)Compile time
const_cast<T>(x)Add or remove const/volatile onlyCompile time
reinterpret_cast<T>(x)Treat the bits of a pointer/reference as a different type (low-level, dangerous)Compile time
dynamic_cast<T>(x)Safe downcast in a polymorphic class hierarchyRun time
(T)x or T(x)C-style / functional cast: tries the casts above until one worksCompile time

static_cast — Your Everyday Cast

static_cast is used for nearly all normal conversions. The syntax static_cast<TargetType>(expression) is long on purpose: it is easy to spot and to search for in code.

#include <iostream>

int main() {
    double x = 7.8;
    int i = static_cast<int>(x);               // 7
    char ch = static_cast<char>(i + 'A');      // 'H'
    int code = static_cast<int>(ch);           // 72
    double ratio = static_cast<double>(3) / 4; // 0.75

    std::cout << i << ' ' << ch << ' ' << code << ' ' << ratio << '\n';
    return 0;
}

Output:

7 H 72 0.75

static_cast refuses conversions that make no sense, for example turning an int* into a double*, or removing const. It is also the standard way to convert between scoped enumerations and integers (see Structures, Unions & Enums) and, for class hierarchies, to convert a derived-class pointer to a base-class pointer (see Inheritance).

const_cast — Removing const

const_cast can only add or remove const (or volatile). Its main legitimate use is calling old code that takes a non-const pointer but never actually modifies the data. This example uses pointers, which are explained in the Pointers chapter; for now just read char* as "address of some text".

#include <iostream>

// An old library function: takes char* but only reads the text
void printTitle(char* text) {
    std::cout << "== " << text << " ==\n";
}

int main() {
    const char* title = "Results";
    // printTitle(title);                    // error: cannot convert const char* to char*
    printTitle(const_cast<char*>(title));    // OK, because printTitle never writes
    return 0;
}

Output:

== Results ==

Warning: const_cast makes the code compile, but if you then modify an object that was originally defined as const, the behavior is undefined. Here the text is a string literal, and writing to it would be UB.

reinterpret_cast and std::bit_cast — Looking at Raw Bits

reinterpret_cast tells the compiler "treat this address as if it pointed to a different type". It does no conversion of the value at all. It is needed in low-level code (device drivers, serialisation), and the one generally safe use for beginners is viewing any object as raw bytes through unsigned char*. For copying the bit pattern of one value into another type, C++20 added std::bit_cast, which is safe and clear.

#include <iostream>
#include <bit>        // std::bit_cast (C++20)
#include <cstdint>

int main() {
    float f = 1.0f;
    auto bits = std::bit_cast<std::uint32_t>(f);   // same bits, viewed as an integer
    std::cout << std::hex << std::showbase << bits << '\n';

    int value = 0x01020304;
    auto* bytes = reinterpret_cast<unsigned char*>(&value);   // look at raw bytes
    std::cout << static_cast<int>(bytes[0]) << '\n';          // 0x4 on little-endian
    return 0;
}

Output (on an x86-64 machine, which is little-endian):

0x3f800000
0x4

0x3f800000 is how IEEE-754 stores 1.0f. Compare this with static_cast<std::uint32_t>(1.0f), which would give the value 1: static_cast converts values, bit_cast copies bits. The byte example prints 0x4 because a little-endian CPU stores the least significant byte first. Using reinterpret_cast to read an object through a pointer to an unrelated type like float* → int* is undefined behavior (it breaks the "strict aliasing" rule); std::bit_cast is the correct tool for that.

dynamic_cast

dynamic_cast checks at run time whether a base-class pointer really points to a particular derived-class object. It only makes sense with classes that have virtual functions, so we will study it in Polymorphism & Virtual Functions.

Why Not Just Use the C-Style Cast?

C++ still accepts the C syntax (int)x and the functional form int(x). They are fine for simple numeric conversions, but they are too powerful: a C-style cast silently tries const_cast, static_cast, and reinterpret_cast (and combinations) until something compiles. It can remove const without you noticing.

#include <iostream>

int main() {
    const int limit = 100;
    int* p = (int*)&limit;   // C-style cast silently removes const
    *p = 200;                // undefined behavior: limit is really const
    std::cout << limit << ' ' << *p << '\n';
    return 0;
}

One possible output (GCC 15):

100 200

The same "variable" appears to have two values at once! The compiler assumed limit could never change and used 100 directly. This is what undefined behavior looks like in practice. If we had written static_cast<int*>(&limit), the compiler would have refused to compile it, protecting us from the bug.

PointC-style cast (T)xC++ named casts
IntentHidden: could be any kind of conversionClear from the name
SafetyCan remove const or reinterpret bits silentlyEach cast can do only its own job
SearchabilityHard to find with a text searchEasy: search for _cast
Run-time checkNeverdynamic_cast provides one

Converting Between Strings and Numbers

A string like "2026" is text, not a number, so no cast can turn it into an int. The standard library provides functions instead (header <string>; we cover std::string fully in Strings).

#include <iostream>
#include <string>

int main() {
    int marks = 87;
    double pi = 3.14159;
    std::string s1 = std::to_string(marks);     // "87"
    std::string s2 = std::to_string(pi);        // "3.141590"

    int n = std::stoi("2026");
    double d = std::stod("9.75");
    int partial = std::stoi("42abc");           // stops at the first non-digit

    std::cout << s1 + "!" << ' ' << s2 << '\n';
    std::cout << n + 1 << ' ' << d * 2 << ' ' << partial << '\n';
    return 0;
}

Output:

87! 3.141590
2027 19.5 42
  • std::to_string on a double uses six decimal places up to C++23, which is why we see 3.141590. (C++26 changes it to print the shortest exact form, like std::format does.)
  • std::stoi, std::stol, std::stoll, std::stod parse from the start of the string and stop at the first invalid character. If no number can be read at all (for example std::stoi("abc")), they throw a std::invalid_argument exception; if the number is too large, std::out_of_range. Exceptions are covered in Exception Handling.

For high-performance parsing without exceptions, C++17 added std::from_chars in <charconv>. It reports errors through a return value and tells you where it stopped:

#include <iostream>
#include <charconv>   // std::from_chars (C++17)
#include <string_view>

int main() {
    std::string_view text = "1234xyz";
    int value = 0;
    auto [ptr, ec] = std::from_chars(text.data(), text.data() + text.size(), value);
    if (ec == std::errc{})
        std::cout << "value = " << value << ", stopped at: " << ptr << '\n';
    return 0;
}

Output:

value = 1234, stopped at: xyz

Common Mistakes

1. Casting After the Division

static_cast<double>(a / b) is too late: a / b has already been done in integers. Cast an operand: static_cast<double>(a) / b.

2. Expecting Rounding

static_cast<int>(2.99) is 2. Use std::lround(2.99) or std::round for rounding.

3. Comparing Signed with Unsigned

-1 < 1u is false. Keep types consistent, heed -Wsign-compare, or use std::cmp_less.

4. Converting a Huge double to int

static_cast<int>(1e10) is undefined behavior because 1010 does not fit in a 32-bit int. Check the range first or use long long.

5. Using const_cast to Modify a Real Constant

Removing const is only safe if the original object was not const.

6. Printing char When You Wanted the Number

std::cout << uc for an unsigned char prints a character. Use static_cast<int>(uc) or the unary plus trick +uc, which promotes it to int.


Interview / GATE Questions

What is printed by std::cout << 'a' + 1;?

98. 'a' (97) is promoted to int, so the result is the int 98, which cout prints as a number. To print b, write static_cast<char>('a' + 1).

If unsigned int x = 0;, what is x - 1?

4294967295 when unsigned int is 32 bits (that is, 232 − 1). Unsigned arithmetic wraps modulo 2N; this is well-defined, not undefined behavior.

What is the type and value of 7 / 2 + 1.5?

double, value 4.5. 7 / 2 is integer division giving 3; then 3 + 1.5 converts 3 to double.

Name the four C++ cast operators and one use of each.

static_cast: numeric conversions such as int → double. const_cast: removing const to call an old API that does not modify the data. reinterpret_cast: viewing an object's raw bytes as unsigned char*. dynamic_cast: run-time-checked downcast in a polymorphic hierarchy.

Why does int x{3.5}; fail but int x = 3.5; compile?

Brace (list) initialisation, introduced in C++11, forbids narrowing conversions. Copy initialisation with = allows the implicit double → int conversion and truncates to 3.

What is the difference between static_cast<std::uint32_t>(1.0f) and std::bit_cast<std::uint32_t>(1.0f)?

static_cast converts the value: the result is 1. std::bit_cast (C++20) copies the bit pattern: the result is 0x3f800000, the IEEE-754 encoding of 1.0.

Is static_cast<signed char>(200) undefined behavior?

No. Converting an out-of-range integer to a signed integer type was implementation-defined before C++20; since C++20 it is defined to wrap modulo 2N, giving -56 for an 8-bit signed char. (Contrast with signed arithmetic overflow, like INT_MAX + 1, which is still undefined.)


In Simple Words

C++ converts types automatically when they meet; know the rules so they don't surprise you, and use named casts when you convert on purpose.

small ints → int before arithmetic         (integral promotion)
int op double → double                     (usual arithmetic conversions)
signed op unsigned (same size) → unsigned  (-1 < 1u is false!)
double → int truncates toward zero         (out of range = UB)
int x{3.5};  → rejected (no narrowing in braces)
static_cast → everyday; const_cast → const only;
reinterpret_cast → raw bits; dynamic_cast → run-time check

We now know how to compute values and control their types. Next, let's use those values to make decisions with Conditional Statements.