# Case expression not constant

• 02-01-2011, 01:29 AM
Derrek
Case expression not constant
hello, im making a simple rpg and this error kept coming up, and i dont know how to fix it. these are the cases i have.

switch (job)
{
case "human": hp << 100;
break;
case "troll": hp << 120;
break;
case "elf": hp << 90;
break;
case "wizard": hp << 80;
break;
}
• 02-01-2011, 09:00 AM
hendrixj
Luckily for you, literal strings don't always convert to constant integers.
The object of the case statement must be an integral type or something that converts to an integral type.
Try:
enum Species { HUMAN, TROLL, ELF, WIZARD };

Let "job" be declared:
Species job;

Then, you have:
switch (job)
{
case HUMAN: hp << 100; break;
case TROLL: hp << 120; break;
case ELF: hp << 90; break;
case WIZARD: hp << 80; break;
}
• 02-01-2011, 11:09 AM
Danny
The labels of a case statement must be of an integral constant type. Therefore, you can't use any other constants, including literal strings. The most effective technique to overcome this is by using enum types, as hendrixj showed.
• 02-01-2011, 01:28 PM
jonnin
I always add a max to my enums.

Something like this:

enum Species { HUMAN, TROLL, ELF, WIZARD, Species_Max };

so you can do this:

for(x = human; x < Species_Max; x++)
....

for(x = human; x <= Wizard; x++)

.... my way, if you add in dwarves later on, nothing else changes (max is still max, its just a different number) whereas if you do it the second way, you have to change ALL the loops and other such references.

You can also do this nicely
sometype container[species_max] using the same principles, never change the size, it grows to fit if you add more stuff.
• 02-01-2011, 05:41 PM
Danny
and while we're at it, C++0x now offers strongly-typed enums and scoped enums:
http://www.informit.com/guides/conte...lus&seqNum=316
• 02-03-2011, 01:31 PM
jonnin
Quote:

Originally Posted by Danny
and while we're at it, C++0x now offers strongly-typed enums and scoped enums:
http://www.informit.com/guides/conte...lus&seqNum=316

I would still give a lot to be able to print the enum's name out or get at it as a string.