Why the output of below code is -127. Why shouldn't it be -1?
#include<stdio.h>
int main(){
int a = 129;
char *ptr;
ptr = (char *)&a;
printf("%d ",*ptr);
return 0;
}
It can be understood as follows:
We all know that the range of (signed) char
is from [-128 to 127]
, now let's break this range into binary format, so, the bits required is 8
(1
Byte)
0
: 0000 0000
1
: 0000 0001
2
: 0000 0010
3
: 0000 0011
...
126
: 0111 1110
127
: 0111 1111
<-- max +ve number as after that we will overflow in sign bit
-128
: 1000 0000
<-- weird number as the number and its 2's Complement are same.
-127
: 1000 0001
-126
: 1000 0010
...
-3
: 1111 1101
-2
: 1111 1110
-1
: 1111 1111
So, now coming back to the question, we had int a = 129;
, clearly 129
when stored inside the char
data type it is going to overflow as the max positive permissible value is 127
. But why we got -127
and not something else?
Simple, binary equivalent of 129
is 1000 0001
and for char
data-type that comes somewhere around,
127
: 0111 1111
-128
: 1000 0000
-127
: 1000 0001
<-- here!
-126
: 1000 0010
...
So, we get -127
when 129
is stored in it.