[C++] Switch case with char array and strings

Joined
Sep 9, 2008
Messages
1,947
Reaction score
390
I have a server that emulates Flyff. It has well over 300 npcs in the game. I want to make a switch case because if statements are too much for that many conditions and I want to save memory as well. The problem is they are in char* format and I get errors trying to switch case them.

How can I do this?
 
Yep, comparison of strings is quite intensive work, try to make #DEFINE's or better: enum's where instead of strings you'd use constants with integer values, then you can make it a switch, but using int comparison over string comparison will save you a lot already :) (probably more then making it a switch, but a switch is good for code structure). If this is possible of course (if it's not user input for example).
 
Can you explain to me exactly how a switch statement will save you memory as opposed to using an if-else chain?

I somewhere heard that switch's are quicker then if-else's (the longer, the more significant). Of course this is micro-optimization, it's also better for the code structure.
 
It depends on your compiler if it really is better - a smart one will see an if/else tree and break after the first match (first if condition to be true). Bad compilers will also evaluate the other elseif's - if you have many options that's quite a bit of work.

Switches on the other hand incorporate a break statement which will make sure no other option is evaluated after a match. Of course, as i said, once this is all compiled the resulting machine code might very well be exactly the same as with an if/else tree.

At any rate it's indeed a micro-optimalisation as Daevius already said.

A better aproach would be to consider why you think you need such a long if/else tree. Generally you are much better off using function references or a simple index matching algorythm.
 
Back