Switch-case错误 | 常量表达式中的值不可用

6
我写了一个简单的例子来解决我在编写程序时遇到的问题。
在程序执行期间,当从函数返回值时,我获得了input1和input2的值,这些值随后永远不会改变。然后,在程序的各种计算过程中稍后,我得到了一个结果,这个结果也再也不能改变。
我试图使用switch-case进行比较,但是我得到了一个错误:“'input1'的值在常量表达式中无法使用”。
#include <iostream>

using namespace std;

char getChar()
{
    char c;
    cin >> c;
    return c;
}

int main()
{
    // it doesn't work
    const char input1 = getChar();
    const char input2 = getChar();

    // it it works
    //const char input1 = 'R';
    //const char input2 = 'X';

    char result = getChar();
    switch(result)
    {
        case input1:
            cout << "input1" << endl;
            break;
        case input2:
            cout << "input2" << endl;
            break;
    }
    return 0;
}
4个回答

2

case标签在编译时需要已知某些内容。变量不能在此上下文中使用。 您将需要一个if...else if...else if...来模拟具有可变运行时值的switch语句。


2

您需要在编译时知道您的情况语句。即

switch(result)
    {
        case 1:
            cout << "input1" << endl;
            break;
        case 2:
            cout << "input2" << endl;
            break;
    }

这些代码行虽然使用了const关键字,但实际上仅表示只读,并未在编译时进行初始化。

// it doesn't work
const char input1 = getChar();
const char input2 = getChar();

以下两行代码之所以能够工作,是因为编译器在你的代码运行之前就将 X 和 R 替换到了 switch 语句中。
// it it works
//const char input1 = 'R';
//const char input2 = 'X';

我建议将您的开关改为if语句。
if(input1)
{}
else if(intput2)
{}

以下代码应该有效:
#include <iostream>

using namespace std;

char getChar()
{
    char c;
    cin >> c;
    return c;
}

int main()
{
    // it doesn't work
    const char input1 = getChar();
    const char input2 = getChar();

    // it it works
    //const char input1 = 'R';
    //const char input2 = 'X';

    char result = getChar();
    if(result == input1){
            cout << "input1" << endl;
    }
    else if(result == input2){
            cout << "input2" << endl;
    }

    return 0;
}

谢谢解释!我以为使用if-else会是一个很好的选择。 - Евгений Куркин

1
< p > case语句中使用的标签必须在编译时对编译器可用,因此您尝试的方法不起作用。

您已将其设置为const,但这仅意味着一旦初始化,它就不会更改。


0

这里我提供另一个无法使用case语句的例子。只是一段代码片段。

switch (val) {
  case SOMECLASS::CONST_X:
     sosomething();
     break;

如果CONST_X是一个静态常量,可以这样定义:static const int CONST_X; 如果你在头文件中定义它,那么case语句就没问题了。但是如果你在实现文件(*.cpp)中定义它,编译器就无法通过。然而,如果你在头文件中定义它,有时会出现链接问题。因此,我的经验告诉我不要在case语句中使用类常量(通常是int类型)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接