为什么C ++ switch语句限制为常量表达式? [英] Why are C++ switch statements limited to constant expressions?

查看:216
本文介绍了为什么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 (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 ++的优势之一是它的静态检查。 $ 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语句限制为常量表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆