int x = 3; float y; y = x;Before being assigned to
y, a copy of the value of x
is automatically converted from type int to type
float
(<type>)(<expression>)
(int)(3.7) would produce 3
int left, total, dummy; float number; // the following is illegal (% must have an int on right) left = total % number; // but the following would work left = total % (int)(number);General note on conversions:
int to float is a widening
conversion.
Widening conversions are commonly regarded as safe (within reasonable limits) and will be permitted in many languages and by many compilers.
float to an int would be
a narrowing conversion.
Narrowing conversions are widely regarded as unsafe (as there is a high possibility for loss of data). In C++ you can still perform many narrowing conversions, but typically a warning will be generated by the compiler if it detects such a conversion.
int x, y;
char a, b;
x = int('T'); // x = 84
y = x + 1; // y = 85
a = char(y); // a = 'U'
b = char(x); // b = 'T'
printf("%c", char(32 + int('a')));
// will print out A