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);
It works because all types narrower than
intwill go under default promotion. Sinceunsigned charandunsigned shortare both smaller than int on your platform, they'll be promoted tointand the result won't overflow ifintcontains22 bits or more (which is the number of bits inCHAR_BIT + 17bits or more (which is the result ofa * 65535plus sign)30 * 65535plus sign). However ifinthas fewer bits then overflow will occur and undefined behavior happens. It won't work ifsizeof(unsigned short) == sizeof(int)eitherDefault 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