Arithmetic and Slice Conversions

Arithmetic and slice conversions will be discussed in this lesson.

We'll cover the following

Arithmetic conversions

There are other conversion rules that are applied for arithmetic operations. In general, automatic arithmetic conversions are applied in the safe direction: from the narrower type to the wider type. Although this rule is easy to remember and is correct in most cases, automatic conversion rules are very complicated, and in the case of signed-to-unsigned conversions, carry some risk of bugs.

The arithmetic conversion rules are the following:

  1. If one of the values is real, then the other value is converted to real.

  2. Else, if one of the values is double, then the other value is converted to double.

  3. Else, if one of the values is float, then the other value is converted to float.

  4. Else, first integer promotions are applied according to the table given in the previous lesson, and the following rules are followed:

    1. If both types are the same, then no more steps are needed.

    2. If both types are signed or both types are unsigned, then the narrower value is converted to the wider type.

    3. If the signed type is wider than the unsigned type, then the unsigned value is converted to the signed type.

    4. Otherwise, the signed type is converted to the unsigned type

Unfortunately, the last rule above can cause subtle bugs:

Get hands-on with 1000+ tech skills courses.