In simple terms, if you mix types of the same rank (in the sequence of int
, long int
, long long int
), the unsigned type "wins" and the calculations are performed within that unsigned type. The result is of the same unsigned type.
If you mix types of different rank, the higher-ranked type "wins", if it can represent all values of lower-ranked type. The calculations are performed within that type. The result is of that type.
Finally, if the higher-ranked type cannot represent all values of lower-ranked type, then the unsigned version of the higher ranked type is used. The result is of that type.
In your case you mixed types of the same rank (int
and unsigned int
), which means that the whole expression is evaluated within unsigned int
type. The expression, as you correctly stated, is now 10 - 4294967254
(for 32 bit int
). Unsigned types obey the rules of modulo arithmetic with 2^32
(4294967296
) as the modulo. If you carefully calculate the result (which can be expressed arithmetically as 10 - 4294967254 + 4294967296
), it will turn out as the expected 52
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…