As we know that arrow keys produces two outputs 224
and 77
or 80
or 72
or 75
.
Code 1:-
int main()
{
int ch,ch1;
ch=getch();
ch1=getch();
printf("%d\n",ch);
printf("%d",ch1);
}
When you press up key
it displays
224
72
Code 2:-
int main()
{
char ch,ch1;
ch=getch();
ch1=getch();
printf("%d\n",ch);
printf("%d",ch1);
}
When you press up key
it displays
-32
72
My question is that, as you can see that the second output is same for both char
and int
, but why the first output i.e. 224
and -32
are different with int
and char
.
Number 224, when stored in signed char
, overflows.
char
typically gets considered as signed char
and can hold values from -128 to 127. When you attempt to store a number beyond those limits, overflow occurs which causes the number to go around from the other end.
You can think of it as filling a jar with water, then emptying out the whole jar when you fill the whole jar, and then go on filling whatever you are left. In this case, you are filling a char
variable with 224
... So;