Search code examples
c++conditional-statementsor-operator

How to execute a block only if all previous conditions were false and execute a specific block if one of them was true?


I'm making a little game in C++, and I'm wondering how to optimize my branching. Look at this code:

if (
  isUpPressed ||
  isDownPressed ||
  isLeftPressed ||
  isRightPressed ||
  isSpacePressed
) {
  if (isUpPressed)
    state |= State::MoveUp;
  if (isDownPressed)
    state |= State::MoveDown;
  if (isLeftPressed)
    state |= State::MoveLeft;
  if (isRightPressed)
    state |= State::MoveRight;
  if (isSpacePressed)
    state |= State::Jump);
} else
  state = State::Still;

What I want to achieve is: if up, down, left, right or space is pressed, set state to the appropriate value. If none of these conditions was true, set the state to State::Still. My code works, but it feels like I'm doing it wrong. There must be a better way. My question is:
How to execute a block only if all of the specified conditions failed, and execute a block specific to each of these conditions if one or several are true, without using nested if and lots of || operators as I did?


Solution

  • As taken from bits and pieces in the comments. Something like this perhaps (assuming none of the movement states holds the value 0)

    State::Value state = State::Value(0);
    if (isUpPressed)
        state |= State::MoveUp;
    if (isDownPressed)
        state |= State::MoveDown;
    if (isLeftPressed)
        state |= State::MoveLeft;
    if (isRightPressed)
        state |= State::MoveRight;
    if (isSpacePressed)
        state |= State::Jump);
    
    if(state == State::Value(0))
        state = State::Still;
    
    if(isOnFire)
        state |= State::Fire;
    

    Alternatively, if you have more blocks of code similar to the movement block, you can create a temp State variable, treat it the same way and merge the temp state and the original state.