Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Is the result of the addition of char type and int type char type or int type?
Is the result of the addition of char type and int type char type or int type?
Suppose the programming language is C/C++.

Generally speaking, the result is an int type. If char is implemented as unsigned char and has the same length as int on the compiler, the result will be unsigned int.

To perform an arithmetic operation, the operand must first be raised to an integer. The so-called integer promotion refers to type conversion according to the following rules:

For bool, (signed/unsigned) char, (unsigned) short and other types, as long as all their possible values can exist in int, they are promoted to int type; Otherwise, it is promoted to unsigned int type. For example, when two signed characters are added, both signed characters will be promoted to int.

The larger char types (wchar_t, char 16_t, char32_t) are upgraded to the smallest type among int, unsigned int, long, unsigned long, long long and unsigned long long, which can accommodate all possible values of the original type.

After integer promotion, if the result types match, no further conversion is required. If both (promoted) operands are signed or unsigned, a small type is converted to a large type. For example, if you add int to long, the result is long.

If one operand is unsigned and the other operand is signed, there are two situations:

Unsigned types are not less than signed types (such as unsigned long and int), and signed ones are converted into unsigned ones. For example, in the original title, if char is implemented as unsigned char with the same length as int, then firstly, the integer lifting char is converted into unsigned int(int can't accommodate all possible values of char), and then the int is added with unsigned int, and then the int is converted into unsigned int, and the final result is unsigned int.

Unsigned types are smaller than signed types, and the result depends on the machine. If all values of an unsigned type can exist in a signed type, the unsigned type is converted to a signed type, otherwise the signed type is converted to an unsigned type.