Q:

Nested if-statements C++

I'm writing a Snake program in C++ (visualisation with JNI) and valid movement buttons are either left (move 90° counter-clockwise) or right (move 90° clockwise).
In every loop of the game loop I retrieve a key event from a GUI interface and move my snake according to that key event, this is how i do this:
if(key_event != NULL){
    if(key_event == LEFT){
        if(moveDirection == UP || moveDirection == DOWN){
            moveDirection = LEFT;
            (moveDirection == UP) ? /*change turn after head*/ : /*change turn after head*/;
        } //else if (moveDir == LEFT || RIGHT)
    } //else if (key_event == RIGHT)
    //...
}

The if with: /*change turn after head*/ is because if the snake is moving down and goes left there is another graphic for the turn then when it's going up and goes left.  
This leads to a lot of if-statements and is not very readible, so I'm wondering if there's a general way to solve nested if-statements like this.
EDIT:
key_event and moveDirection are enums.

A:

It feels like Finite State Machine is what you need here. You can define keys as events, snake positions as states and describe transitions from one state into another depending on the event (what key pressed). That will pretty much solve the problem and use transition table instead of nested if statements and make your implementation less error prone. Boost Statechart Library can help you implement it quickly.

A:

I would personally have another function to apply the move.
if(key_event != NULL){
    if(key_event == LEFT){
       moveLeft();
    }
    ...
}

void moveLeft()
{
  switch(moveDirection)
  {
    case UP:
    case DOWN:
      moveDirection = LEFT;
      break;
    case ...
  }
}

I use switch case, in my opinion it is more read-able for this example rather than if.. else if.. else if...
The point is, when you have nested loops, see if you can break some of it into a function to simplify the problem.
I hope this helps.

A:

Most likely the code will be more readable if you factor sections of the if checks into functions. Without seeing the full context of the work being done it's hard to say for sure, but something like get_new_direction(event, direction) would probably be a good start. When the components of the if checks are well named functions it will help both readability and also possibly nesting levels.

