Implicit Type Conversion

Last modified by Microchip on 2023/11/09 09:06

In many expressions, the type of one operand will be temporarily promoted to the larger type of the other operand.

int x = 10;
float y = 2.0, z;
z = x* y;                //x promoted to float

The above example is a special case of the overall concept of implicit type conversion. In virtually any arithmetic operation, the data types of the operands will be temporarily converted to the data type of the largest operand. For example, if we are multiplying an integer by a float, the integer will be promoted to a float for the duration of the evaluation of the expression.

As we see here, we are multiplying an integer with a value of 10 by a float with a value of 2.0. In this case, the int is promoted to a float, so the 10 becomes 10.0. Once the expression has been evaluated giving us a float result of 20.0, the variable x goes back to being an int. This implicit type conversion helps to ensure that no precision is lost as part of the operation.

Implicit Arithmetic Type Conversion Hierarchy

Implicit Conversion

Example Implicit Type Conversions

ExpressionImplicit Type ConversionExpression's TypeResult
-xx is promoted to intint5
x*-2Lx is promoted to long because -2L is a longlong10
8/xx is promoted to intint-1
8%xx is promoted to intint3
8.0/xx is promoted to double because 8.0 is a doubledouble-1.6

Here are some examples of real-world implicit type conversions. For each example, assume that x is defined as a short int with a value of -5.

  • In the first case, even though x is the only operand, it is promoted to int for the operation because int is the fundamental data type for most operations.
  • In the second case, x is promoted to long since the literal is explicitly specified as a long, which is larger than short.
  • In the third case, we are dividing an int by a short, so the short is promoted to int.
  • The same holds true for the fourth case.
  • The last one has x promoted to double because the numerator is type double. Since we didn't explicitly specify the numerator as a long8.0L, the compiler assumes it is the largest unmodified floating point type which is double, as opposed to a modified type: long double.