Search code examples
cintturbo-c

Why 32767+1 gives -32768 in Turbo C?


When I add 32767 to 1 in an integer variable in Turbo C, i get -32768 whereas I should get 32768.

I want to know why this happens.


Solution

  • 32767 and 1 both fit in an int, so they're constants of type int. In Turbo C int has range of -32768 to 32767 (they're 16-bit 2's complement signed integers). When you add an int to an int, there are no promotions on either side, and the result will be also of type int. However 32767 + 1 is not representable in a signed int - it is outside the limits of the type. This is called signed integer overflow.

    According to C standard when signed integer overflow occurs, the behaviour of the program is undefined. In this case it wraps the value around; e.g. when you add 1 to 0b0111111111111111, you get 0b1000000000000000, which is interpreted as -32768.

    However the C standard does not mandate any wraparound on signed integer overflow - anything may happen. Your program can even behave like the result is positive 32768 (even though not representable by a 16-bit int - this is actually quite probable on 32-bit and 64-bit processors - the compiler knows that since the number never is going to overflow, the compiler can use a wider register for it). Or your program may crash with an exception, or it may cause demons fly out of your nose.