1

So its been like 12-14 years since I have done any c++ development and this weekend I decided to give it a try again to prototype some gaming stuff but this error was the first one that I ran into that made no sense to me.

I had this switch statement:

void Game::handleEvents()
{
  SDL_Event event;
  SDL_PollEvent(&event);

  switch (event.type)
  {
  case SDL_MOUSEMOTION:
    bool mouseInUiNow = isInRect(sideUiBackground, event.motion.x, event.motion.y);

    if (mouseInUiNow && !mouseInUi)
    {
      std::cout << "mouse enter ui" << std::endl;
      mouseInUi = true;
    }
    else if (!mouseInUiNow && mouseInUi)
    {
      std::cout << "mouse exited ui" << std::endl;
      mouseInUi = false;
    }

    break;

  default:
    break;
  }
}

Which resulted in this error:

error: cannot jump from switch statement to this case label default:

After googling a little, I figured out that I needed to add braces around the case statement:

void Game::handleEvents()
{
  SDL_Event event;
  SDL_PollEvent(&event);

  switch (event.type)
  {
  case SDL_MOUSEMOTION:
  {
    bool mouseInUiNow = isInRect(sideUiBackground, event.motion.x, event.motion.y);

    if (mouseInUiNow && !mouseInUi)
    {
      std::cout << "mouse enter ui" << std::endl;
      mouseInUi = true;
    }
    else if (!mouseInUiNow && mouseInUi)
    {
      std::cout << "mouse exited ui" << std::endl;
      mouseInUi = false;
    }

    break;
  }

  default:
    break;
  }
}

However I was not really able to understand why. Knowing how to fix it is one thing but I would really like to understand the why too.

Could someone please explain to me why this is needed in this case but in other cases the braces are not needed (naively is seems like the creation of a variable bool mouseInUiNow = isInRect(sideUiBackground, event.motion.x, event.motion.y); is causing the braces to be needed, but not sure why)?

ryanzec
  • 27,284
  • 38
  • 112
  • 169
  • 4
    **TL;DR** of that is *you cannot jump over a variable declaration via `switch`/`case`* – hlt May 13 '18 at 10:39

0 Answers0