• C

Switch Statement

It's a very simple question, but solution is eluding me.

How do you switch on a char[] or char*
E.g. I have to switch based on a char*, but the switch statement doesn't take char* ??

Any replies ???
kapoorvAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
vardisConnect With a Mentor Commented:
This code might solve your problem

void main()
{
      char letter[] = "Some text";
      char *n = "Some text";
      
      switch(n[0])
      {
      case 'a':   /*note the single quotes*/
      DoSomething();
      }

/* or you can use this instead*/
      switch(letter[0])
      {
      case 'a':     /*note the single quotes*/
      DoSomething();
      }
}

0
 
bing031398Commented:
You CANT!!!

What you CAN do is shift through every element with an if statement

char Stuff[][] = {};  /* the cases*/

for( i = 0; i < MAX_MEMBERS; ++i )
{
    if( strncmp( Stuff[i], VAR_TO_CASE ) == 0 )
    {
        /* do what you want */
    }
}
0
 
kapoorvAuthor Commented:
Bing..
UR answer is logically and I was going to implemet it, but it then struck me that the whole comparison is in a for loop and for each value I have to perform a different action.

The only choice I see is using the standard if..then..else condition.


0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
kapoorvAuthor Commented:
Bing..
UR answer is logically and I was going to implemet it, but it then struck me that the whole comparison is in a for loop and for each value I have to perform a different action.

The only choice I see is using the standard if..then..else condition.


0
 
alexoCommented:
kapoorv, there is a really elegant solution involving tables.
I'm goint to submit it as a comment because the question is locked by vardis.  If you like it, reopen the question for me.

Say you have 5 strings and 5 related actions.
You put each related action in a function:

    void Action1() { /* ... */ }
    void Action2() { /* ... */ }
    void Action3() { /* ... */ }
    void Action4() { /* ... */ }
    void Action5() { /* ... */ }

Now, you set up a table of strings, terminated by a guard entry:

    char* strings[] = { "string1", "string2", "string3", "string4", "string5", NULL };

And a table of pointers to functions:

    typedef void (*PFUNC)();
    PFUNC funcs[] = { Action1, Action2, Action3, Action4, Action5, NULL };

Then you have a loop:

    for (i = 0; strings[i]; ++i)
    {
        if (strcmp(strings[i], my_string) == 0)
        {
            funcs[i]();
            break;
        }
    }

Now, if you want to make it even more elegant, combine the 'strings' and 'funcs' variables into a struct.
0
 
ozoCommented:
/*I sometimes like to set up parallel tables with*/
#define table \
x(Action1,"string1",{ /* ... */ }) \
x(Action2,"string2",{ /* ... */ }) \
x(Action3,"string3",{ /* ... */ }) \
x(Action4,"string4",{ /* ... */ }) \
x(Action5,"string5",{ /* ... */ }) \
z
#define x(a,s,f) void a()f
#define z
table
#undef x
#undef z
#define x(a,s,f) s,
#define z NULL
char* strings[] = {
table
};
#undef x
typedef void (*PFUNC)();
#define x(a,s,f) a,
PFUNC funcs[] = {
table
};
0
 
marvinmCommented:
yeah, what ozo said
0
 
alexoCommented:
ozo, what happens when you want to put a breakpoint in one of the Action() funcs?
0
 
ozoCommented:
In such cases I might set up only *strings[] and PFUNC funcs[] that way.
0
 
alexoCommented:
Incidently, the current issue of CUJ suggests a similar technique:
    http://www.cuj.com/current/qa.html
0
 
newexpertCommented:
Attn ozo:  Pity IOCCC is no longer running.
Attn alexo:  Excellent solution but what if the person want to operate on local variables in the switch statement.  It would be tedious to pass them all to actions() don't you think?

This is a traditional way of writing it.

#include <stdio.h>
#include <string.h>

typedef struct { int num; char *name; } ACTION;
ACTION list[] = { { 1, "do1" }, {2, "do2"},
                  { 3, "do3" }, {0, NULL } };
int lookup(char *request)
 {
  ACTION *i;
  for (i = list; i->name != NULL; i++)
   if (strcmp(i->name, request) == 0) return i->num;
  return 0;
 }

int function(void)
 {
  char input[MAGIC_NUMBER];
  int i, j, k;
  char c, d, e;
  gets(line); /* read a string */
  switch (lookup(input))
   {
    case 1: i = 1; c = 'a'; break; /* anything */
    case 2: i = j = k = 0; /* anything */
    case 3: c = d = e = '\0'; break; /* anything */
    default: printf("unknown action");
   }
  return i+j+k+c+d+e;
 }

hope you get the idea.
0
 
ozoCommented:
I thought it was still running
http://reality.sgi.com/csp/ioccc/

BTW, the table macro can also be used to construct the actions locally:

#define x(a,s,f)\
if( strcmp(s,my_string) == 0){\
 f; \
}else
#define z { printf("unknown action"); }
0
 
alexoCommented:
newexpert, an interesting idea.  Works even better with bsearch() if the data is sorted.

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.