c++ - 为什么这个 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);
导致需要大括号,但不知道为什么)?
解决方案
推荐阅读
- ejs - <%= %> 标签会改变变量的类型吗?传递的变量在我的函数中不起作用
- python - 找不到满足 actionlib==1.11.13 要求的版本
- asp.net - 实体框架 DbContext 正在尝试插入已经存在的数据
- python - 如何保持 2 列数据帧的 pandas groupby 计数为零?
- java - Try ... Catch 没有捕获 Exception 并且仍然给我运行时错误
- string - 如何在bash中用乱序的字母grep字符串?
- haxe - 在 Haxe/Starling 中是否有编程方式在运行时更改 vsync?
- python - 如何从多个图形显示动画
- gwt - 全屏 Libgdx HTML5 无法在移动设备上运行
- python - Gunicorn:工人无法启动