2

I have executed this program on 32bit Windows 7 OS with Turbo C/C++ editor.

#include<stdio.h>
#include<conio.h>

void main()
{
    int a,b,c,d,e;
    clrscr();

    a = 25000;
    b = 10000;

    c = a + b;

    printf(" The value of c = %d\n", c );

    d = 5000;

    e = c - d;

    printf(" The value of e is %d\n", e );

    getch();
}

When I print c I get the value -30536, because the value 35000 crosses the max value. But when I use the same c in the expression 'e= c - d;' , I get the correct value as 30000. How is this possible?

Rohit S
  • 395
  • 4
  • 18

1 Answers1

4

Let's kick the decimal and our brain and use binary and CPU. The int is 16 bit here

Expression 25000 + 10000 (add the binary code very simple)

 01100001 10101000 = 25000
+00100111 00010000 = 10000
 10001000 10111000 = -30536

10001000 10111000 is the result which is negative 30536 as first bit is signed bit

Now expression -30536 - 5000 (-30536 + (-5000) )

 10001000 10111000 = -30536
+11101100 01111000 = -5000 
 01110101 00110000 = 30000

01110101 00110000 this result is positive 30000

Or -30536 - 5000 you can use 2's complement method to subtract. I won't explain it here.

Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184