c++ - c ++ switch语句:对案例进行分组并为每个案例提供特定说明
问题描述
考虑以下代码:
int main()
{
const int a = 9;
switch (a)
{
case 9:
// since a is 9, this ("good") should be printed
std::cout << " good " << std::endl;
case 4:
// since a is not 4, this ("bad") should not be printed
std::cout << " bad " << std::endl;
// for both a==9 or a==4, this should be printed
{
std::cout << " always print me " << std::endl;
break;
}
}
}
结果应该是:
good
always print me
但是,这是行不通的。有没有办法在 C++ 中做到这一点?谢谢!
解决方案
switch
除了 using 之外,没有办法在-statement中执行您要求的操作goto
:
#include <iostream>
int main()
{
const int a{ 9 };
switch (a)
{
case 9:
std::cout << "good\n";
goto foo;
case 4:
std::cout << "bad\n";
goto foo;
foo:
std::cout << "always print me\n";
break;
}
}
推荐阅读
- java - 面临有关 java 应用程序中内存泄漏的问题。我想在代码的第 2 行关闭 ServerSocketChannel.open()
- huggingface-transformers - 为什么三个嵌入结果与 Transformer 模型如此不同?
- if-statement - 千、百万、十亿和万亿的自定义数字格式
- android - 如果华为设备同时支持 GMS 和 HMS 核心,那为什么 HMS 核心不工作?
- ansible - 适用于生产环境的 Ansible 修补订单/库存逻辑
- plc - 在 TwinCAT 3 PLC 上读取循环时间
- telegram - 如何使用 Telethon 在 Telegram 中编辑消息?
- discord.py - Discord.py 授权让机器人将某人添加到服务器?
- c++ - C++/CLI 包装器项目中的未定义行为
- python - pyodbc 错误:打印调用中缺少括号