DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

Thread: Case expression not constant

1. Registered User
Join Date
Feb 2011
Posts
1

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;
}

2. Registered User
Join Date
Oct 2007
Posts
369
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;
}

3. 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.

4. Senior Member
Join Date
Dec 2003
Posts
3,366
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++)
....

instead of this:

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.

5. 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

6. Senior Member
Join Date
Dec 2003
Posts
3,366
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.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise
 Questions? Contact us. C++ Web Development Wireless Latest Tips Open Source