How the overflow arises!

I looked up scripting languages and saw the unlimited precision capability of the integer format. It immediately made me think how overflows are handled in C!

C language uses 16 bit to represent variable type int. Most significant bit is used to represent the sign  If the most significant bit is zero then the value is treated as positive, if it is 1 then negative. For example, consider the 16-bit integer number representation, which is illustrated  as follows:

Binary Number                                                   Decimal Equivalent

0000 0000 0000 0000                                                     0

0000 0000 0000 0001                                                     1

………….

0111 1111 1111 1111                                                    32,767
If I add 1 to 32,767, we would expect the result to be 32768. However, the value becomes -32,768 as follows:
1000 0000 0000 0000                                                 -32,768

 

#include <stdio.h>

void main(void)
{
    int pos = 32767;
    int neg = -32768;

    printf("%d + 1 is %d", pos, pos+1);
    printf("%d - 1 is %d", neg, neg-1);
}

Output:

32767 + 1 is -32768

-32768 – 1 is 32767

leave your comment