【问题标题】:switch statement multi character constantswitch 语句多字符常量
【发布时间】:2016-01-14 14:09:36
【问题描述】:

我正在尝试将其转换为 switch 语句

if (codeSection == 281)
    cout << "bigamy";
else if (codeSection == 321  ||  codeSection == 322)
    cout << "selling illegal lottery tickets";
else if (codeSection == 383)
    cout << "selling rancid butter";
else if (codeSection == 598)
    cout << "wounding a bird in a public cemetery";
else
    cout << "some other crime";

// Actual switch statement
switch (codeSection)
{
    case '281':
        cout << "bigamy" << endl;
        break;

    case '321':
    case '322':
        cout << "selling illegal lottery tickets" << endl;
        break;

    case '383':
        cout << "selling rancid butter" << endl;
        break;

    case '598':
        cout << "wounding a bird in a public cemetery";
        break;

    default:
        cout << "some other crime"<< endl;

}

编译器说 switch 语句多字符常量,并给我一个黄色警告,但仍然编译。我的问题是这种情况应该只是 char 形式吗?像案例'2'

【问题讨论】:

  • 您可能应该知道编译器 警告 是您应该考虑的事情,但不一定会破坏任何东西。事实上,许多警告都可以关闭(并非必须如此)。另一方面,错误会阻止您的代码正确编译或运行。

标签: c++ switch-statement


【解决方案1】:
case '281':

应该是

case 281:

其余部分类似,否则编译器“认为”您尝试使用多字符常量,这可能不是您想要的。

case 不一定是char。实际上,它必须是与转换和整数提升后的条件类型相同类型的常量表达式,请参见例如http://en.cppreference.com/w/cpp/language/switch.

【讨论】:

  • ...原因是,用单引号括起来将其指定为字符文字,而在这种情况下不使用它们使其成为整数文字。
  • @JasonMc92 确实,不鼓励使用 afaik 多字符常量,因为它们的值是实现定义的。
  • 是的,你是对的。我在该主题上找到了this article
  • @JasonMc92 哈哈,好笑,我看了同一个:)
  • 谢谢,原来如此。
猜你喜欢
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 2011-07-10
  • 2011-12-19
  • 1970-01-01
  • 2023-01-16
相关资源
最近更新 更多