为什么case语句只接受常量? [英] Why do case statements only accept constants?

查看:223
本文介绍了为什么case语句只接受常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中的switch语句必须用常量写成的事实背后的原因是什么?

What is the reason behind the fact thet switch statements in C++ have to be written with constants?

让我们来看看下面的代码:

Let's take a look at the following code:

switch(variable)
{
    case 1:
    case 2:
    case 3:
    case 4:
        //Code 1
        break;

    case 5:
    case 6:
    case 7:
    case 8:
        //Code 2
        break;

    default:
        //Code 3
        break;
}

在其他语言中,例如PAWN(C-Like脚本语言)可以这样编写此代码:

In other languages, for example PAWN (C-Like scripting language), I could write this code down as such:

switch(variable)
{
    case 1 .. 4:
        //Code 1
        break;

    case 5 .. 8:
        //Code 2
        break;

    default:
        //Code 3
        break;
}

C ++ switch语句的背后原因是soo ..石器时代?

What is the reason behind the fact the C++ switch statement is soo.. from the Stone Age? (Not to mention we can't use variables.)

即使经过这么多年的变化和更新...

Even after so many changes and updates over all those years...

推荐答案

没有技术原因C switch语句无法更新到使用范围。 gcc已经有了这个扩展。

There's no technical reason that C switch statements couldn't be updated to use ranges. gcc already has an extension for this.

http://www.n4express.com/blog/ ?p = 1225

这些值有很好的理由是常数;允许进行各种优化,如跳转表。

There are good reasons for the values to be constant; that allows for all sorts of optimizations such as jump tables.

这篇关于为什么case语句只接受常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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