Implicit Type Conversion
- If unexpected type occurs in expression, ambiguity must be resolved by implicit type conversion or
an error occurs
- When there is a known rule for
converting the unexpected type to the expected type, that rule will be invoked
and computation can proceed.
- E.g., when the types on the left and right sides of an assignment statement
do not match, the assignment statement is allowed to proceed if and only
if there is a way provided to convert from the Rvalue type to the Lvalue
type
- For native
types, there is generally a way to convert from smaller types to larger types
but not the reverse
- Beware changing between signed annd unsigned types
- When mixed types appear in an
arithmetic expression, the types will be converted to the largest type appearing
in the expression
char a, b;
int m, n;
float x, y;
unsigned int u, v;
m = a; // OK
a = m; // error
x = m; // OK
u = m; // dangerous - possibly no warning
x = a + n; // result of (a + n) is type int
// converted to type float for assignment
- When in doubt, make type conversions explicit.
|