Question

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.

Was it helpful?

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

OTHER TIPS

That's because the range of char is -128 to 127. Which means you can assign positive values of range 0 to 127 and negative values of -1 to -128.

The help/man page says that getch returns int: not char.

Depending on the compiler, char can default to either a signed char or an unsigned char. The range for a signed char is -128..127, an unsigned char 0..255. In this case, it is a signed char. The Microsot compiler has a compiler switch for this.

If 224 is assigned to an unsigned char, you will get 224. If it is assigned to an unsigned char, you will get 224-256 = -32.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top