Type Coercion and Casting

 C++ allows you to mix data types in expressions.

Type Coercion

Used when you are mixing data types. If you assign a value to a variable that is not the same type as the variable, C++ may do the conversion for you; this is coercion.

int i;
float f;
i = 5.6 // i will be 5
f = 10 // f will be 10.0
f = 5.3 / 2 + 1 // f will be 5.3/2.0 + 1.0 
f = 5 / 2 + 4.5 // f will be 6.5

 

Type Casting

Used when the programmer wants to explicitly convert one data type to another. It shows the programmer's intention as being very clear.

i = 5.2 / f; // warning "loss of precision"
 
i = int(5.2 / f) // no warning but still loss
f = float(3 * i) 

Next Slide