GLFW_KEY_UP and GLFW_KEY_RIGHT not working

Hello, I recently implemented this code:

void GLFWCALL handleKeypress (int key, int press) { switch (key) { case GLFW_KEY_ESC: exit(1); case GLFW_KEY_RIGHT: rotate_x+=5; case GLFW_KEY_LEFT: rotate_x-=5; case GLFW_KEY_UP: rotate_y+=5; case GLFW_KEY_DOWN: rotate_y-=5; } }

where rotate_x and rotate_y are both global variables as shown here:

float rotate_x=0,rotate_y=0;

The routine above is used to change these two lines of code glRotatef (rotate_x, 1.0, 0.0, 0.0); glRotatef (rotate_y, 0.0, 1.0, 0.0);

When I press the left or the down keys, everything works as expected, but pressing the right or the up keys does absolutely nothing.

However if I comment out:

//case GLFW_KEY_LEFT: //rotate_x-=5; and

case GLFW_KEY_DOWN: rotate_y-=5; and runs the program again, both start to working!. Pressing the up key produces the expected result, however pressing the right key does not, it seems to be rotating my object over two axis simultaneously.

So, what I am doing wrong? Thanks for the help.

You need to add break in C if you don’t want a switch statement to continue executing every line after the selected case label.

1 Like

One of the great footguns of C and C++ that I still occasionally fall victim to.

I tend to use the following style to mitigate the problem:

switch (key) {
    case GLFW_KEY_ESC: {
    } break;

    case GLFW_KEY_RIGHT: {
    } break;

    case GLFW_KEY_LEFT: {
    } break;

    case GLFW_KEY_UP: {
    } break;

    case GLFW_KEY_DOWN: {
    } break;

    default: {
        // Do nothing

but for some reason nobody seems to agree with me…

1 Like

Not sure I’ll use it but it’s very legible. I like it and wouldn’t mind working in code written that way.


Well, when I don’t forget, I tend to use it but without the {}

1 Like