Type Compatibilities

  1. As a general rule, you cannot store value of one type in a variable of another type.

  2. 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.

  3. 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 turns out to be a whole number.

  4. C++ often does not check for data mismatches carefully enough, the programmer should be more careful not to abuse the language.

  5. If you must convert data 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) takes the value in x and converts it to type int. The value is obtained from x by dropping the fractional part.
    On the other hand if n is an integer, one can use float(n) to cast its value to a float, or use double(n) to cast its value to a double. In either cases, a decimal point and trailing zeros are added to the integer.

    The C++ standard added a few new type-conversion operators: const_cast, dynamic_cast, reinterpret_cast, and static_cast. You should be encouraged to use these new type-conversion operators. Consequently, static_cast<int>(x) can be used to cast a float or double to an integer, and static_cast<float>(n) or static_cast<double>(n) can be used to cast the value in integer n to either a float or a double.

    Casting does not change the type of the variables nor the value they contain. Only the particular copies of their values are changed. Of course casting can be done on expressions and not only variables.