Many C and C++ operators cause implicit type conversions, which change the type of an expression. When you add values having different data types, both values are first converted to the same type. For example, when a short int value and an int value are added together, the short int value is converted to the int type. It can result in loss of data if the value of the original object is outside the range representable by the shorter type.
Implicit type conversions can occur when:
You can perform explicit type conversions using the C-style cast, the C++ function-style cast, or one of the C++ cast operators.
#include <iostream> using namespace std; int main() { float num = 98.76; int x1 = (int) num; int x2 = int(num); int x3 = static_cast<int>(num); cout << "x1 = " << x1 << endl; cout << "x2 = " << x2 << endl; cout << "x3 = " << x3 << endl; }
The following is the output of the above example:
x1 = 98 x2 = 98 x3 = 98
The integer x1 is assigned a value in which num has been explicitly converted to an int with the C-style cast. The integer x2 is assigned a value that has been converted with the function-style cast. The integer x3 is assigned a value that has been converted with the static_cast operator.
Related References