I need help understanding what the syntax of this particular if statement accomplishes

Viewed 112

Im trying to follow along and break down a the source code for a pacman clone. There is an if statement that im confused about.

void PacMan::queueDirection(Direction dir)
{
    if (!directions.empty())
    {
        if (dir == -directions.front()) //this statement
        {
            std::queue<Direction> clear;
            std::swap(directions, clear);
        }
    }

    if(directions.size() < 2)
        directions.push(dir);
}

My question is what does the - infront of -directions.front() do? directions is a queue. Does it multiply the reference returned by front() by -1? Thanks for the help - ill post a link below to the github where the whole project is. https://github.com/HexagonNico/Pac-Man/blob/master/PacMan.cpp if that tickles your fancy.

1 Answers

The code you have pasted seems to have the following intent:
In case the Direction instance at the head of the queue, directions, is a negative of the value supplied as the argument of this function, the queue is cleared and the supplied argument is enqueued.

The type Direction in this case is an enum as defined in the header Directions.h

enum Direction
{
    Up = 1,
    Down = -1,
    Left = 2,
    Right = -2,
    Unset = 0
};

Negating a Direction instance, in this case, just gives us its diametric opposite.

As an example, consider that the value Direction::Up is at the head of the queue at the time the function is invoked and the argument to the function is Direction::Down. In this case the queue directions will be cleared. I have added an example to make this point clearer.

Related