There is code:
#include <iostream>
int main(){
unsigned char a = 4, b = 255;
int g = (unsigned char)a + (unsigned char)b;
std::cout << g << std::endl;
return 0;
}
Result:
259
Why the result is 259, not 3? If there are added two unsigned char variables, there should be overflow, result should be 3 and then it should convert from unsigned char 3 to int 3.
unsigned char to integer assignment is no problem, but the other way around will have over flow problems at the high end.
When adding two char or unsigned char variables, both are subject to integer promotions, which converts them to type int . In either case the sum is 140 and is of type int . This fits into unsigned char , so the resulting value of unsigned_sum is 140.
When an unsigned int and an int are added together, the int is first converted to unsigned int before the addition takes place (and the result is also an unsigned int ).
There is no difference. unsigned and unsigned int are both synonyms for the same type (the unsigned version of the int type).
The addition operation will first promote its operands to int
, before doing the addition. This is how C works. If you want to truncate, you need to assign it back into a narrower type, such as unsigned char
.
Integer arithmetic is never performed on data types smaller than int
. For example, for types smaller than int
e.g. if two types char
and short int
are added, they are promoted to int
before any arithmetic operation and result is an integer type. If one of the types happened to be larger than int e.g long long int
and int
then int gets promoted to long long int
and the result is long long int
.
(§ 4.5/1) - An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With