Type conversion vs Type cast
- Conversion: creates new value (typically primitives)
- Sometimes cast to unsigned int is a cast or a conversion (g++ is cast)
- Cast: Changes label, or way object is seen, data is not changed
Categories:
- Explicit vs implicit
- Widening vs narrowing
- Checked vs unchecked
Explicit vs Implicit
- Explicit: Requires you to use the actual syntax to do
- Implicit: opposite
- Example: passing int into float param
- Most implicit casts are upcasts
static_cast
in C++ is ironically a conversion
C++ Implicit Conversion Rules
- If either operand is a long double, convert other to long double
- “ double
- “ float
- “ unsigned long int
- Operands are long int and unsigned int and long int can represent unsigned int, then convert unsigned int to long int
Implicit conversion: coercion
PL lingo: a coercion that converts a narrow type into a wider type is a type promotion. (Int→Long, etc.)
Widening vs Narrowing