Re: something like switch in c
From: Darrell Grainger (darrell_at_NOMORESPAMcs.utoronto.ca.com)
Date: 07/08/04
- Next message: John Hanley: "Re: using fscanf"
- Previous message: Universe: "Re: Static vs. Dynamic typing (big advantage or not)---WAS: c.programming: OOP and memory management"
- In reply to: lior l: "something like switch in c"
- Next in thread: josh: "Re: something like switch in c"
- Reply: josh: "Re: something like switch in c"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 8 Jul 2004 16:07:44 GMT
On Wed, 7 Jul 2004, lior l wrote:
> Hi,
>
> I wanted to know if there is a way to program ( or there is an
> existing command) that will act like switch but also on strings (char
> *).
You need to specific the programming language. My first assumption is that
you are talking about C or C++. If that is the case then there is no
simple solution for what you want.
The brute force concept would be:
if(strcmp(...)) {
:
} else if(strcmp(...)) {
:
} else {
:
}
This would have the same layout but not the most efficient way to do
things. The numerous function calls and the cost of each compare could
become quite expensive.
You could create a lookup table but that gets a little more tricky. At
least if you want it to be as readable. Something like:
char lookuptable[][80] = {
"joe",
"mike",
:
};
To make it readable, you need:
enum {JOE, MIKE, ...};
The problem is that if I insert a name in the middle of the lookup table,
I have to insert the name in the enum list as well. Additionally, I still
have to search the list, find the index of the name I'm looking for then
use a switch with the enum values.
The fastest way might be to create a hash table. You pass the string into
a has function and it returns an int. You can then switch on the int. You
will still need the enum (or macros) to make it readable.
The question you have to ask is what is important? Readability,
maintainability, performance, etc.. Find a balance that works for you.
> example:
>
> switch(name)
> {
> case "joe":
> :
> :
> break;
> case "mike":
> :
> :
> break;
> :
> :
> :
>
-- Send e-mail to: darrell at cs dot toronto dot edu Don't send e-mail to vice.president@whitehouse.gov
- Next message: John Hanley: "Re: using fscanf"
- Previous message: Universe: "Re: Static vs. Dynamic typing (big advantage or not)---WAS: c.programming: OOP and memory management"
- In reply to: lior l: "something like switch in c"
- Next in thread: josh: "Re: something like switch in c"
- Reply: josh: "Re: something like switch in c"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|