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'
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.
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With