Home > Software design >  Why is else if producing different results compared to a switch?
Why is else if producing different results compared to a switch?

Time:10-22

I have a simple piece of code that detects keystrokes using ncurses.

As I understand, 1 keypress pushes 3 values into the buffer. Where the 3rd value differentiates between arrow keys for example.

So when pressing any of the 4 arrows on the keyboard, the first 2 values pushed into the buffer should be similar \033, and [. But the 3rd value is unique to the arrow (A for up, B for down, C for right or D for left). Therefore, when mapping actions to keystrokes, we're depending on the 3rd value.

When trying to assess which arrow was pressed I tried both an if else ladder and a switch. The if else ladder works perfectly. But the switch seems to fire multiple cases on each keypress.

Here's the working code (if else) -

char first = getch(); //returns \033
char second = getch(); //returns [
char third = getch(); // returns A or B or C or D

if(third == 'A'){
printf("Up Arrow Pressed");
}
else if(third == 'B'){
printf("Down Arrow Pressed");
}
else if(third == 'C'){
printf("Right Arrow Pressed");
}
else if(third == 'D'){
printf("Left Arrow Pressed");
}

Here's the code that isn't working (Case) -

char first = getch(); //returns \033
char second = getch(); //returns [
char third = getch(); // returns A or B or C or D


switch(third){
    case('B'):
        printf("\nDOWN");
    case('C'):
        printf("\nRIGHT");
    case('A'):
        printf("\nUP");
    case('D'):
        printf("\nLEFT");
    default:
        printf("default");
    }

This is the output when cases are used and I press the down key:

enter image description here

CodePudding user response:

if you don't break; at the end of a case the next case is executed.

CodePudding user response:

If You Don't Use break at the end of each case then the cases that you write after the true case will also be executed.

  • Related