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:
-
If one of the values is
real
, then the other value is converted toreal
. -
Else, if one of the values is
double
, then the other value is converted todouble
. -
Else, if one of the values is
float
, then the other value is converted tofloat
. -
Else, first integer promotions are applied according to the table given in the previous lesson, and the following rules are followed:
-
If both types are the same, then no more steps are needed.
-
If both types are signed or both types are unsigned, then the narrower value is converted to the wider type.
-
If the signed type is wider than the unsigned type, then the unsigned value is converted to the signed type.
-
Otherwise, the signed type is converted to the unsigned type
-
Unfortunately, the last rule above can cause subtle bugs:
Get hands-on with 1400+ tech skills courses.