开关大小写错误 |的值在常量表达式中不可用

switch-case error | the value of is not usable in a constant expression

本文关键字:表达式 常量 错误 大小写 开关      更新时间:2023-10-16

我写了一个简单的例子来解决我在编写他的程序时遇到的问题。

在程序执行期间,当从函数返回值时,我得到 input1 和 input2 的值,然后这些值永远不会改变。然后过了一会儿,在程序过程中进行了各种计算后,我得到了一个也不再可更改的结果。

我正在尝试使用开关大小写比较它们,但我得到一个错误"'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;
}

您必须在编译时知道您的 case 语句。 即

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;
}

case标签要求在编译时已知的somenthin。变量不能在此上下文中工作。您将需要一个if... else if... else if...来模拟具有可变运行时值的 switch

语句

case语句中使用的标签必须在编译时可供编译器使用,因此您尝试的内容不起作用。

你已经把它const了,但这只是意味着它一旦初始化就不会改变。

在这里,我给出了另一个无法使用 case 语句的示例。只是一个代码片段。

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

如果CONST_X,则说静态常量 int CONST_X; 如果您在标头中定义它,那么 case 语句就可以了。但是,如果在实现文件 (*.cpp) 中定义,则将无法传递编译器。 但是,如果您在标题中定义,有时会遇到链接问题。 所以我的经验告诉我不要在 case 语句中使用类常量(通常是 int 类型)。