5

I'm trying to convert this into a switch statement

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;

}

The compiler says switch statement multi character constant, and gives me a yellow warning but still compiles. My question is are the case supposed to be only in char form? like case '2'

1
  • You should probably know that a compiler warning is something that you should take under advisement, but isn't necessarily going to break anything. Many warnings can be turned off, in fact (not that they necessarily should). Errors, on the other hand, prevent your code from compiling or running correctly. Commented Oct 15, 2015 at 23:15

1 Answer 1

6
case '281':

should be

case 281:

and similarly for the rest, otherwise the compiler "thinks" that you try to use a multi-character constant, which is not what you probably want.

A case doesn't have to be a char. In fact, it must be a constant expression of the same type as the type of condition after conversions and integral promotions, see e.g. http://en.cppreference.com/w/cpp/language/switch.

Sign up to request clarification or add additional context in comments.

6 Comments

...the reason being, enclosing something in single quotes specifies it as a character literal, while leaving them off in this case makes it an integer literal.
@JasonMc92 True, afaik multi-character constants are somehow discouraged, as their value is implementation-defined.
Yes, you're right. I found this article on the topic.
@JasonMc92 Ha ha, funny, I was glancing at the same one :)
Thank you, that was exactly it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.