Home > Mobile >  why minimum possible integer minus one becomes maximum possible integer in c
why minimum possible integer minus one becomes maximum possible integer in c

Time:11-24

I know that c works in two's complement but still i can't undrstand how the program below gives me 2147483647 as output.

#include<stdio.h>
int main(){

int a=-2147483648;
a-=1;
printf("%d",a);

}

CodePudding user response:

Becuase an int can't contains the value -2147483648 - 1, so it result in an integer overflow, which leads to undefined behaviour. Undefined behaviour can result in anything.

CodePudding user response:

minimum number in twos comlement is 100000...0 if you reduce one from that it means computer will add -1 to it -1 in twos complement is: 11111...1 so if you add them the answer is 0111111...1 which is maximum integer or 2147483647

  •  Tags:  
  • c
  • Related