使用switch和case语句时出错C2131

时间:2016-03-12 05:25:07

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

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

错误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语句,有人可以请我直截了当吗? 感谢。

1 个答案:

答案 0 :(得分:0)

case看起来像case 10:。在表壳中放置一个变量(不是常量表达式)会给出错误,因为在编译代码时需要知道这些情况的值。另外,如果您未将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;
}
相关问题