really simple question here. have simple program adding 2 numbers , printing out sum of numbers (below). when running program, works expected , prints out 40 000 20 000 + 20 000. when change int a, b , sum short a,b , sum, -25 536 answer. can explain why happens? have idea, love hear knows it. reading.
int a, b, sum; = 20000; b = 20000; sum = a+b; printf("%d + %d = %d\n", a, b, sum);
on system, short
presumably 16 bits, range of values -32768
32767
. 20000 + 20000
larger maximum value, causes overflow, results in undefined behavior.
if change unsigned short
, range becomes 0
65525
, , addition work. in addition, overflow well-defined unsigned
integers, wraps around using modular arithmetic, e.g. (unsigned short)65535 + 2 = 1
.
Comments
Post a Comment