How do you have logical or in case part of switch statment?(你如何有逻辑或万一的开关语句的一部分?)
问题描述
如果您有一个 switch 语句,并且希望在值为一个值时运行某些代码或另一个值,您该怎么做?以下代码始终使用默认情况.
If you have a switch statement and want certain code to be run when the value is one value or another how do you do it? The following code always goes to the default case.
#include <iostream>
using namespace std;
int main()
{
int x = 5;
switch(x)
{
case 5 || 2:
cout << "here I am" << endl;
break;
default:
cout << "no go" << endl;
}
return 0;
}
推荐答案
像这样:
switch (x)
{
case 5:
case 2:
cout << "here I am" << endl;
break;
}
被称为跌倒".
只是指出在发布的代码中执行 default 案例的原因是 5 || 的结果2 是 1 (true).如果您在发布的代码中将 x 设置为 1,则 5 ||2 案例将被执行(参见 http://ideone.com/zOI8Z).
Just to point out that the reason the default case is executed in the posted code is that the result of 5 || 2 is 1 (true). If you set x to 1 in the posted code the 5 || 2 case would be executed (see http://ideone.com/zOI8Z).
这篇关于你如何有逻辑或万一的开关语句的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你如何有逻辑或万一的开关语句的一部分?
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
