Search code examples
ccastinglong-integerparenthesesshort

Unsure why this cast works


i have the following code:

unsigned short a, b, c, d;
unsigned long result;

a = 30000;
b = 40000;
c = 50000;
d = 60000;

result = (unsigned long)(a + b + c + d) / 4;
printf("result is %i", result);

The result of this is (30000 + 40000 + 50000 + 60000) / 4 = 180000 / 4 = 45000 which is correct. But i wonder why. I would expect the addition of unsigned shorts to overflow because it is done in 16 bit and after the addition the overflowed result is converted to unsigned long and then divided by 4.

What am i missing here?


Solution

  • Your shorts were promoted to ints before addition.

    http://en.cppreference.com/w/cpp/language/implicit_conversion (the link is about C++, but C rules are basically same)

    Integral promotion

    ...arithmetic operators do not accept types smaller than int as arguments, and integral promotions are automatically applied...