Why are C++ switch statements limited to constant expressions?(为什么 C++ switch 语句仅限于常量表达式?)
问题描述
在我意识到语句需要保持不变之前,我想在 switch 语句中使用宏函数.示例(不编译):
I wanted to use macro functions in switch statements before I realized the statements need to be constant. Example (does not compile):
#define BAND_FIELD1(B) (10 * B + 1)
...
#define BAND_FIELD7(B) (10 * B + 7)
int B = myField % 10;
switch (myField) {
case BAND_FIELD1(B):
variable1[B] = 123;
break;
case BAND_FIELD7(B):
variable7[B] = 321;
break;
...
}
我宁愿使用 if .. else:
I rather had to use if .. else:
if (myField == BAND_FIELD1(B)
variable1[B] = 123;
else if (myField == BAND_FIELD7(B)
variable7[B] = 321;
为什么 C++ switch 语句仅限于常量表达式?
Why are the C++ switch statements limited to constant expressions?
推荐答案
C++ 的优势之一是它的静态检查.switch
语句是一个静态控制流结构,其强大之处在于能够(静态地)检查是否所有案例都已被考虑,以及能够合理地对案例进行分组(例如,通过公共部分).
One of the strengths of C++ is its static checking. The switch
statement is a static control flow construct, whose power lies in the ability to check (statically) whether all cases have been considered, and in being able to group cases sensibly (e.g. fall through common parts).
如果您想动态检查条件,您已经可以使用多种技术(if
语句、条件运算符、关联数组、虚函数等等)来实现.
If you want to check conditions dynamically, you can already do so with a variety of techniques (if
statements, conditional operators, associative arrays, virtual functions, to name a few).
这篇关于为什么 C++ switch 语句仅限于常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 C++ switch 语句仅限于常量表达式?


基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07