Search code examples
c++switch-statementgetch

C++, Up arrow detected as both up and right


I defined the four arrow keys as such-

#define UP_ARROW    72
#define LEFT_ARROW  75
#define DOWN_ARROW  80
#define RIGHT_ARROW 77

And the keys are being checked using _getch(), as such

char key = _getch();
if (key == 0 || key == -32)
{
    key = _getch();
    switch (key)
    {
    case UP_ARROW:
        //These are functions not relevant to the problem
        //up(1);
    case DOWN_ARROW:
        //down(1);
    case LEFT_ARROW:
        //left(1);
    case RIGHT_ARROW:
        //right(1);

        //Pressing up will print out "test", which should not happen
        printf("test");
    }
}

As commented, pressing up will call anything in the RIGHT_ARROW case. Did I do something wrong?


Solution

  • You need a break; statement to stop continuation of a switch.

    You can use the break statement to end processing of a particular case within the switch statement and to branch to the end of the switch statement. Without break, the program continues to the next case, executing the statements until a break or the end of the statement is reached. In some situations, this continuation may be desirable.

    http://msdn.microsoft.com/en-us/library/66k51h7a.aspx