Reputation: 1
I thought the following code might cause an overflow since a * 65535
is larger than what unsigned short int
can hold, but the result seems to be correct.
Is there some built-in mechanism in C that stores intermediary arithmetic results in a larger data type? Or is it working as an accident?
unsigned char a = 30;
unsigned short int b = a * 65535 /100;
printf("%hu", b);
Upvotes: 0
Views: 89
Reputation: 41753
It works because all types narrower than int
will go under default promotion. Since unsigned char
and unsigned short
are both smaller than int on your platform, they'll be promoted to int
and the result won't overflow if int
contains 22 bits or more (which is the number of bits in CHAR_BIT + 17
bits or more (which is the result of a * 65535
plus sign)30 * 65535
plus sign). However if int
has fewer bits then overflow will occur and undefined behavior happens. It won't work if sizeof(unsigned short) == sizeof(int)
either
Default promotion allows operations to be done faster (because most CPUs work best with values in its native size) and also prevents some naive overflow from happening. See
Upvotes: 2