Type Compatibilities
-
As a general rule, you cannot store value of one type in a variable of another type
-
Attempt to do so will result in reactions that can differ from one compiler to the next.
Some may issue an error message, some simply give a warning message, and some may not even object at all
-
Examples of type mismatch (or mixing data types):
int int_variable;
int_variable = 2.99;
Most (but not all) compilers truncates 2.99 to 2 and assign it to the integer variable int_variable
int int_variable;
double double_variable = 2.00;
int_variable = double_variable;
This last assignment statement is illegal since the value of a double variable cannot
be assigned to an integer variable even when the value comes out even
-
C++ often does not check for data mismatches carefully enough, the programmer should be more careful
not to abuse the language
-
If you must convert between int and float or double, then you should use the appropriate casting operators.
If x is of type float or double, then int(x) is of type int.
It is obtained from x by dropping the fractional part.
On the other hand if x is an integer, one can use float(x) to cast it to a float,
or use double(x) to cast it to a double.
In either case, a decimal point and trailing zeros are added to the integer.