Type Conversions & Casts
Implicit conversions (automatic)
The compiler converts types when needed:
double d = 5; // int → double (5.0) safe ✅
int i = 3.99; // double → int (3) loses data ⚠️
int x = 7 / 2; // 3 (integer division!)
double y = 7 / 2.0; // 3.5
Arithmetic promotion rules (simplified)
char,short,bool→ promoted tointin arithmetic- If one operand is
double, the other becomesdouble - If one is
unsignedand the othersignedof the same size, the signed one becomes unsigned ⚠️
unsigned int u = 1;
int s = -1;
s < u // false! -1 becomes 4294967295
Explicit conversions: C++ casts ✅
| Cast | Use for |
|---|---|
static_cast<T>(x) | normal conversions: double↔int, int↔enum, base↔derived (known safe) |
const_cast<T>(x) | removing const (rarely needed; dangerous) |
reinterpret_cast<T>(x) | reinterpret bits/pointers (low-level only) |
dynamic_cast<T>(x) | safe downcasting in class hierarchies (Unit 9) |
int total = 10, count = 4;
double avg = static_cast<double>(total) / count; // 2.5
Why not C-style casts (int)x?
- They try several casts silently — hiding dangerous ones
- Hard to search for in code
- Named casts show your intent
Rounding vs truncation
static_cast<int>(3.99)→ 3 (truncates toward zero)std::round(3.5)→ 4,std::floor(3.99)→ 3,std::ceil(3.01)→ 4 (<cmath>)std::lround(x)returns alongdirectly
Converting text ↔ numbers
std::stoi("42"), std::stod("3.5"), std::to_string(42) (Unit 6.5)
Example
#include <cmath>
#include <iostream>
int main() {
int total_marks = 247, subjects = 3;
std::cout << "Integer division: " << total_marks / subjects << '\n';
std::cout << "With static_cast: " << static_cast<double>(total_marks) / subjects << '\n';
double price = 499.75;
std::cout << "truncate: " << static_cast<int>(price)
<< ", round: " << std::lround(price)
<< ", floor: " << std::floor(price)
<< ", ceil: " << std::ceil(price) << '\n';
char c = 'a';
std::cout << "'a' as int: " << static_cast<int>(c)
<< ", uppercase: " << static_cast<char>(c - 32) << '\n';
int negative = -1;
unsigned int one = 1;
// Comparing signed with unsigned: -1 is converted to a huge unsigned value
std::cout << "(unsigned)-1 = " << static_cast<unsigned int>(negative) << '\n';
std::cout << "-1 < 1u ? " << std::boolalpha << (static_cast<unsigned int>(negative) < one) << '\n';
bool flag = static_cast<bool>(42); // any non-zero number is true
std::cout << "bool(42) = " << flag << '\n';
return 0;
}
/* Output:
Integer division: 82
With static_cast: 82.3333
truncate: 499, round: 500, floor: 499, ceil: 500
'a' as int: 97, uppercase: A
(unsigned)-1 = 4294967295
-1 < 1u ? false
bool(42) = true
*/