views:

893

answers:

5

My code looks like this:

char * decode_input(char ch)
{
        switch(ch) {
                case 'g':
                        return "get";
                        break;
                case KEY_F(9):
                        return "quit";
                        break;
                default:
                        return "unknown";
                        break;
        }
}

Any clues? Thanks in advance.

A: 

It looks like KEY_F(9) must evaluate to something that is outside the range of a char.

McWafflestix
+2  A: 

In this case, KEY_F(9) is evaluating to something outside the range of char. The switch statement is assuming that because its argument is a char, that all case labels will be also. Changing the switch to read switch((unsigned int)ch) will cure it.

RBerteig
+3  A: 

A char is a number between -128 and 127. KEY_F(9) probably is a value outside of that range.

Use:

  • unsigned char, or
  • int, or
  • (char) KEY_F(9)

Or even better, use a debugger and determine sizeof(KEY_F(9)) to make sure it's a byte and not a short.

razzed
Casting KEY_F(9) to char might loose information depending on the implementation of that macro. Also, char is either signed or unsigned depending on the platform defaults and often compiler switches.
RBerteig
True true, and it's been a while since I played in C. I always used types for string characters anyway and always used unsigned char for the type, so I haven't run into this ever...
razzed
Casting it to char worked a charm -- thanks very much.
Alistair
Note that casting to char will remove the compiler error, but it will likely not behave correctly!
razzed
+7  A: 

Well, KEY_F(9) would be 273 (see curses.h) which exceeds the range of char (-128,127).

Kousik Nandy
The range of char depends on whether char is signed or unsigned. However, if curses.h is the source of the macro, then it is outside the range either way.
RBerteig
A: 

What everyone else said regarding the range for char.

I remember this from my early days writing C... you're probably calling decode_input from a loop, right? If the user presses something like F9, you're going to get two bytes in the keyboard buffer - and the first byte will be 0x0.

Jeffrey Kemp