Eddie Kusturica - 1 year ago 102

C Question

Really simple question here. I have a really simple program for adding two numbers and printing out the sum of those numbers (below). When running the program, it works as expected and prints out 40 000 for 20 000 + 20 000. But when I change int a, b and sum to **short** a,b and sum, I get -25 536 as an answer. Anyone who can explain why this happens? I have an idea, but would love to hear it from someone who knows it. Thanks for reading.

`int a, b, sum;`

a = 20000; b = 20000; sum = a+b;

printf("%d + %d = %d\n", a, b, sum);

Answer Source

On your system, `short`

is presumably 16 bits, so the range of values is `-32768`

to `32767`

. `20000 + 20000`

is larger that the maximum value, so this causes overflow, which results in undefined behavior.

If you change to `unsigned short`

, the range becomes `0`

to `65525`

, and the addition will work. In addition, overflow is well-defined with `unsigned`

integers, it simply wraps around using modular arithmetic, e.g. `(unsigned short)65535 + 2 = 1`

.