4.2) Type Conversion
Operators always act on values of the same type. Thus, in expressions with mixed types, the compiler will perform implicit type conversion.
for example, in an arithmetic operation on an int
and a float
, the int
is promoted to a float
so that the operation in fact takes place on a pair of float
values, yielding a float
result.
Sometimes, it is necessary to perform type conversion explicitly. This is done by means of a cast. C++ compilers permit three different syntaxes for this, as illustrated in the examples below.
// C++ static casting operator int n = static_cast<int>(x); float z = static_cast<float>(x*x + y*y); // Functional notation int n = int(x); float z = float(x*x + y*y); // Traditional 'C-style' casting int n = (int) x; float z = (float) (x*x + y*y);