0

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?

Prasad
  • 5,946
  • 3
  • 30
  • 36
C. Prasch
  • 3
  • 2
  • 1
    Possible duplicate of [Usual arithmetic conversions in C : Whats the rationale behind this particular rule](https://stackoverflow.com/questions/8937676/usual-arithmetic-conversions-in-c-whats-the-rationale-behind-this-particular-r) – Retired Ninja Oct 07 '17 at 21:56

1 Answers1

1

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...

Community
  • 1
  • 1
HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Sorry for comming back so late on this topic and thanks for the answer. I have read about integral promotion before, but somehow not correctly realized that this is happening here. But this means that if the above code is used in an embedded system where int is 16 bit the calculation will fail with overflow, correct? – C. Prasch Oct 13 '17 at 06:32
  • @C.Prasch Yes. (Not exactly fail, but rather UB will happen.) To make it work, you should cast (one of the) operands to the `unsigned long` first. – HolyBlackCat Oct 13 '17 at 15:42