Type Conversions
how does the conversion work when writing mixed mode expression types
using operands of the primitive types, it converts the narrower type to the wider type
unsafe type conversion
value of the respective type is converted to teh value of another type that does not equal the original value
when are explicit type conversions helpful?
when we would like to to perform floating point division in an expression that contains two integers
what is a design decision concerning arithmetic expressions?
whether an operator can have operands of different types
what type of conversion is an int to a float?
widening conversion; some precision may be lost
syntax for writing the cast
static_cast<type to cast> (value to cast)
what does a broad range of coercions reduce?
the benefits of type checking
underflow/overflow
result of the operation cannot be rep in object where it is to be stored
are narrowing conversions always safe?
NO- sometimes the magnitude of the converted value is changed in the process ex: converting the double 1.5E25 to an int will result in a value that is not in any way related to the original value
WHY must c++ define for implicit operand type conversions
b.c the underlying computer hardware does not have binary operations that take operands of different types
ex of safe type conversion
bool to char bool to int bool to double char to int char to double int to double
explicit type conversion
both widening and narrowing; also called casts
what must c++ define for implicit operand type conversions
c++ allows for mixed mode expressions, must define conventions for implicit operand type conversions
implicit type conversion
coercion -- initiated by the compiler or run time
what happens when two operands are not of the same type and is legal is the language?
compiler must choose one of them to be coerced and generate the code for that coercion
widening conversions
converts a value to a type that can include at least approx of all values of the original type ex: int to a double
narrowing conversion
converts a value to a type that cannot store even approx of all the values of the original type ex: double to a float b/c the range of a double is much larger than that of a float
safe type conversions
converts the value to an equal value or to the best approx of an equal value
ex of unsafe tc
double to int double to char double to bool int to char int to bool char to bool
how is precision lost with widening conversions?
ex: integers are stored in 32 bits, which allows at least 9 decimal digts of precision float is also stored as 32 bits, with only about 7 digits of precision b.c the space is used for hte sign and expo can lose precision like this
errors in expressions: what is responsible for them?
limitations of computer arithmetic and limitations of arithmetic are responsible
are widening conversions safe?
nearly always; the approx mag. of the converted value is maintained