Search code examples
ccharintoutputarrow-keys

producing output of arrow keys


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 keyit 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.


Solution

  • 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;

    • 224 first fills 127,
    • then you are left with 224 - 127 = 97,
    • one more (97 - 1 = 96) and you are at -128 now,
    • you end up at -128 + 96 = -32