Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement multi character constant

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'

like image 953
Jimmy Huang Avatar asked Oct 15 '15 23:10

Jimmy Huang


People also ask

What is multi-character character constant?

Multi-character constants can consist of as many as four characters. For example, the constant '\006\007\008\009' is valid only in a C++Builder program. Multi-character constants are always 32-bit int values. The constants are not portable to other C++ compilers.

Do switch statements work with characters?

A switch works with the byte , short , char , and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character , Byte , Short , and Integer (discussed in Numbers and Strings).

What is multi-character constant in C++?

Multi-Character Literal in C/C++ A single c-char literal has type char and a multi-character literal is conditionally-supported, has type int, and has an implementation-defined value. Example: 'a' is a character literal. "abcd" is a string literal. 'abcd' is a multicharacter literal.

Can we use same constant in two different switch cases?

The switch statement can include any number of case instances. However, no two constant-expression values within the same switch statement can have the same value.


1 Answers

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.

like image 200
vsoftco Avatar answered Sep 21 '22 13:09

vsoftco