This is happening because of basically limits.When the value get exceed the data type limit that cause overflow.
Normally a signed integer data can ranges between -2,147,483,648 to 2,147,483,647.
Let's get into deep, signed integer data uses 4 bytes to store data which is 32-bits of memory.
In signed integer data type 1st-bit in 32-bits is reserved for sign, which represents the stored number is positive or negative.
Remaining 31-bits are used to store the data.
once again
1st-bit is sign-bit
31-bits are data-bits
if the sign-bit is 0 it represents positive number.if the sign-bit is 1 it represents negative number.
Based on the limit of the positive number that can be stored in signed integer data type is 2,147,483,647.
2,147,483,647 ->0 (+ve) 1111111111111111111111111111111(31-bit)
The first bit 0 represents this number is positive
and the other bits are data bits which represents this number 2,147,483,647 in binary.
One more thing to note,by analyzing the binary value you can notice that all the 31-bits are one which represent it is the maximum value that can be stored in 31-bits.
So let's now get into your question.
It works. unsigned goes up to 2147483648. integer goes up to -2147483648. But why does it become negative?
First of all maximum value that can be stored in unsigned is 4,294,967,295 which is equal to 2^32-1.
Let consider this example code.
#include <stdio.h>
int main() {
int a=2147483647;
printf("%d\n",a);
a++;
printf("%d\n",a);
return 0;
}
Output:
2147483647
-2147483648
In this code the value a stores the value 2147483647.and I tried increment it by one I'm getting -2147483648 instead of 2147483648.
This is because, if you convert 2147483648 this number in binary you will get:
2147483648 ->1 (-)ve 0000000000000000000000000000000(32-bit)
The leading one need to be get stored in data bits only,but it get overflowed to sign-bit.the sign-bit used to represent the number sign.
Because of that 1 overflowed into sign-bit the stored number is considered as negative number.Negative numbers are stored in memory in the form of 2's compliment of its corresponding positive value.
If you convert this the binary of this positive value 2147483648 in 2's compliment you will get this value
-2147483648->1 (-ve) 0000000000000000000000000000000(32-bit)
This is the value which get stored in memory,so you got this (-ve) 2147483648 reasonly.
int
and definitively not for all integer types. – Theonaint
overflow ofval *= 2;
(identified by many) and printing anint val
using%15u%15x%15o
whenval < 0
. – Rote