【问题标题】:Error C2131 using switch and case statements错误 C2131 使用 switch 和 case 语句
【发布时间】:2016-03-12 05:25:06
【问题描述】:

编译以下代码时,我收到以下错误消息:

错误 C2131 表达式未计算为常量

这出现在所有“案例”行上,例如

case  (x == 10):

这是代码:

#include <iostream>
using namespace std;
int main()
{

    int x;

    cout << "Please enter your value for x" << endl;
    cin >> x;
    cout << "The value you entered for x is " << x << endl;

    switch (x)
    {
        case  (x == 10) :

        {
            x = x + 10;
            cout << "x is " << x << endl;
        }

        case (x == 20) :

        {
            x = x + 20;
            cout << "x is " << x << endl;
        }

        case (x == 30) :
        {
            x = x + 30;
            cout << "x is " << x << endl;
        }

        case:

        {
            cout << "x is " << 2 * x << endl;
        }
    }
}

我意识到我一定是错误地使用了 switch 语句,有人可以纠正我吗? 谢谢。

【问题讨论】:

  • 您是否尝试查看任何示例代码?有任何关于 C++ 的教程或书籍吗?

标签: c++ visual-studio debugging visual-studio-debugging


【解决方案1】:

case 看起来就像 case 10:。在 case 中放置一个变量(不是常量表达式)会给你一个错误,因为在编译代码时需要知道 case 的值。此外,如果您不将break 放在case 的末尾,它将链接所有其他语句,直到遇到中断或switch 的末尾。比如下面的代码会显示12;

switch (1)
{
case 1:
    cout << "1";
case 2:
    cout << "2";
break;
case 3:
    cout << "3";
}

如果您想处理任何没有大小写的值,请使用default,而不是空大小写。

switch (x)
{
    //case statements
default:
    cout << x * 2;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 2011-08-15
    相关资源
    最近更新 更多