首页 > 解决方案 > 为什么这个 switch case 需要 C++ 中的大括号?

问题描述

因此,自从我进行任何 c++ 开发以来已经有 12 到 14 年了,这个周末我决定再次尝试对一些游戏内容进行原型制作,但这个错误是我遇到的第一个错误,这对我来说毫无意义。

我有这样的switch声明:

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;
  }
}

这导致了这个错误:

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

谷歌搜索了一下后,我发现我需要在 case 语句周围添加大括号:

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;
  }
}

但是我真的不明白为什么。知道如何解决它是一回事,但我也很想了解原因。

有人可以向我解释为什么在这种情况下需要大括号,但在其他情况下不需要大括号(天真地似乎创建一个变量bool mouseInUiNow = isInRect(sideUiBackground, event.motion.x, event.motion.y);导致需要大括号,但不知道为什么)?

标签: c++

解决方案


推荐阅读