The object type determines the value of the object. This raises a question: what will happen when we try to assign a value out of its value range to a specified type object? The answer depends on the type of signed.
Or unsigned
.
For unsigned
Type, the compiler must adjust the out-of-bounds value to meet the requirements. The compiler will set this value to unsigned
Evaluate the modulo of the number of possible values of the type, and then obtain the obtained value. For example, 8
Bit unsigned char
The value range is from 0.
To 255
(Including 255
). If it is assigned a value out of this range, the compiler will take this value to 256
The value after the modulus. For example, if you try
Storage to 8
Bit unsigned char
, The actual value is 80.
Because 80
Is 336
For 256
The value after the modulus.
For unsigned
Type, the negative number is always out of its value range. Unsigned
Type objects may never save negative numbers. Negative numbers are assigned to unsigned in some languages.
Type is invalid, but in C ++
Is valid. C ++
, Assign the negative value to unsigned
The object is completely legal, and the result is the value after the negative number is calculated for the number of values of this type. Therefore, if-1
Assigned to 8
Bit unsigned char
The result is 255.
Because 255
Yes-1
For 256
The value after the modulus. When the value that exceeds the value range is assigned to signed
The compiler determines the value actually assigned. In practice, many compilers process signed
Type and unsigned
The type is similar. That is to say, the value is the value after the modulo operation on the number of values of this type. However, we cannot guarantee that the compiler will process signed in this way.
Type.