The representation of 2147483647 ie INT_MAX is 0x7FFFFFFF
.
If you add 1, you'll get an undefined behaviour.
This said, in practice, if you add 1, you'll get 0x80000000
ie -2147483648.
I don't know why you expect -1 as its binary encoding is 0xFFFFFFFF
.
#include <stdio.h>
#include <errno.h>
int main(){
int val1 = 2147483647;
int val2 = val1+1;
int x;
printf("errno before : %d\n",errno);
scanf("%d",&x); //enter 2147483648 or a larger value
printf("errno after : %d\n\n",errno);
printf("val1 = %d (0x%X)\n", val1, val1);
printf("val2 = %d (0x%X)\n", val2, val2);
printf("x = %d (0x%X)\n", x, x);
return 0;
}
Output :
errno before : 0
errno after : 34 //0 if the entered value is in the range of 4-bytes integer
val1 = 2147483647 (0x7FFFFFFF)
val2 = -2147483648 (0x80000000)
x = 2147483647 (0x7FFFFFFF)
The reason why you get x=2147483647
is that scanf
clamps the value to the possible range.
If you check errno
after scanf
call, you will see that it is equal to ERANGE
(code 34)