开关大小写错误 |的值在常量表达式中不可用
switch-case error | the value of is not usable in a constant expression
我写了一个简单的例子来解决我在编写他的程序时遇到的问题。
在程序执行期间,当从函数返回值时,我得到 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 类型)。
相关文章:
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- gcc和clang在表达式是否为常量求值的问题上存在分歧
- 使用自动推导的 lambda 参数作为常量表达式
- 生成提升::hana::set 的常量表达式问题
- 为什么不能用常量表达式声明数组?
- 不是 lambda 函数中的常量表达式
- 函数调用在常量表达式中必须具有常量值
- 错误:constexpr 变量'struct2Var'必须由常量表达式初始化
- 如何在常量计算表达式中获取编译时错误?
- 关于在需要常量表达式的上下文中使用的glvalue常量表达式的问题
- 生成 constexpr 字符串表,不能产生常量表达式
- 整体模板参数。错误:在常量表达式中使用'this'
- 如何在满足常量表达式的同时将整数传递给指针,传递给 std::array<double、integer>?
- 编译器错误:函数调用在常量表达式中必须有一个常量值
- 错误:'new'不能出现在常量表达式中
- 我可以写出小于 -0.5 两个 ulps 的常量表达式双精度吗?
- 编译器在传递 const 变量时返回错误:模板参数不是常量表达式
- 为什么我不能在非常量表达式上使用此模板阶乘函数?
- C++ 使用变量而不是常量表达式初始化数组