01 / 20
int double

Type Conversions
& Casts in C++

Learn how C++ converts between types implicitly and explicitly, why narrowing conversions are dangerous, and how to use casts safely.

C++ Programming

What Is a Type?

Every variable in C++ has a type that tells the compiler two things: how much memory to allocate and how to interpret the bits stored there. Different types hold different ranges of values.

int
Whole numbers. Typically 4 bytes (32 bits).
double
Decimal numbers. 8 bytes (64 bits), with fractional precision.
char
A single character. 1 byte. Can be signed (\(-128\) to \(127\)) or unsigned (\(0\) to \(255\)).

Implicit vs Explicit Conversions

C++ performs type conversions in two ways. Understanding the difference is the foundation of writing safe, predictable code.

Implicit (Automatic)
The compiler converts types for you behind the scenes. Also called coercion. You write no special syntax.
Explicit (Cast)
You tell the compiler exactly what conversion to perform using cast syntax. This signals intent and prevents surprises.

The Promotion Ladder

When you mix types in an expression, C++ promotes the narrower type to the wider type. Data flows upward safely:

long double double float long / long long int WIDER NARROWER Safe: no data loss

The Core Rule

1
Truncation: assigning a double to an int drops the decimal part. \(3.99\) becomes \(3\).
2
Overflow: assigning a large int to a short wraps around unpredictably.
3
Sign loss: assigning a negative int to an unsigned int yields a huge positive number.

Visualizing Narrowing

double
\(3.14159\)
8 bytes / 64 bits narrowing int
\(3\)
4 bytes / 32 bits
\(.14159\)
lost! int x{3.14}; // Compiler ERROR: narrowing conversion Brace initialization {} prevents narrowing at compile time

Widening vs Narrowing

Widening Narrowing
Direction Small type → Large type Large type → Small type
Data loss? No Possible
Example int → double double → int
Implicit OK? Yes, always safe Risky: use explicit cast
Brace init {} Allowed Compile error

C++ Cast Operators

C++ provides four named cast operators. For introductory code, you will primarily use static_cast. The old C-style cast (int)x still works but is discouraged.

static_cast
The standard, safe cast for conversions the compiler already knows about. Use this one.
dynamic_cast
For polymorphic class hierarchies. Checks types at runtime.
reinterpret_cast
Low-level bit reinterpretation. Rarely needed, dangerous.
const_cast
Adds or removes const. Use sparingly with legacy APIs.

Using static_cast

// Syntax: static_cast<TargetType>(expression) // Example: explicit double → int double pi = 3.14159; int rounded = static_cast<int>(pi); // 3 // Example: int division → double result int a = 7, b = 2; double result = static_cast<double>(a) / b; // 3.5

Step-by-Step Checklist

1
Identify the types: what type is the source value, and what type does the destination expect?
2
Check the direction: is it widening (safe) or narrowing (risky)?
3
If widening: let the compiler handle it implicitly. No cast needed.
4
If narrowing: use static_cast<T>() to make it explicit. This prevents compiler warnings and signals intent.
5
Prefer brace init {}: for variable declarations, use int x{val} to catch accidental narrowing at compile time.

Example 1: Integer Division Fix

Problem: dividing two integers gives an integer result, even when you want a decimal answer.

// Bug: integer division truncates int total = 7; int count = 2; double avg = total / count; // 3.0, not 3.5! // Fix: cast one operand to double double avg = static_cast<double>(total) / count; // 3.5 ✓

Example 2: Extracting a Character Code

Scenario: you want to see the numeric ASCII value of a character, or convert a number back to a character.

// char → int (widening: safe, implicit) char letter = 'A'; int code = letter; // 65 — no cast needed // int → char (narrowing: needs explicit cast) int value = 66; char ch = static_cast<char>(value); // 'B' // Dangerous: large int → char int big = 300; char oops = static_cast<char>(big); // overflow!

Example 3: Brace Init Protection

C++11 brace initialization catches narrowing conversions that old-style = lets through silently.

// Old style: compiles with a warning (or silently!) double d = 3.14; int x = d; // x = 3, decimal lost silently // Brace init: compiler ERROR int y{d}; // ERROR: narrowing conversion // Correct fix: explicit cast then brace init int z{static_cast<int>(d)}; // OK: intent is clear

Common Mistakes

✕ Using C-Style Casts
Writing (int)x instead of static_cast<int>(x). C-style casts bypass safety checks and are harder to search for in code.
✕ Ignoring Compiler Warnings
Dismissing "possible loss of data" warnings. These are the compiler telling you about narrowing: fix them with a cast or redesign.
✕ Forgetting Integer Division
Writing 7/2 and expecting \(3.5\). Both operands are int, so the result is \(3\). Cast one operand to double first.

Summary Table

Conversion Type Safe? Action
int → double Widening Yes Implicit OK
double → int Narrowing No static_cast
int → char Narrowing No static_cast
char → int Widening Yes Implicit OK
int → unsigned Narrowing (sign) Risky static_cast + validate
float → double Widening Yes Implicit OK

Question 1 of 5

What is the value of x after this code runs?
double d = 9.78; int x = d;

Question 2 of 5

Which line will cause a compiler error due to narrowing?

Question 3 of 5

What does static_cast<double>(7) / 2 evaluate to?

Question 4 of 5

Which cast operator should you use for standard type conversions in everyday C++ code?

Question 5 of 5

Assigning char c = 'A'; followed by int n = c; is an example of: