Solved

Switch Statement

Posted on 1998-08-04
13
330 Views
Last Modified: 2011-08-18
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 ???
0
Comment
Question by:kapoorv
  • 4
  • 3
  • 2
  • +4
13 Comments
 

Expert Comment

by:bing031398
Comment Utility
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
 

Author Comment

by:kapoorv
Comment Utility
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
 

Author Comment

by:kapoorv
Comment Utility
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
 

Accepted Solution

by:
vardis earned 50 total points
Comment Utility
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
 
LVL 11

Expert Comment

by:alexo
Comment Utility
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
 
LVL 84

Expert Comment

by:ozo
Comment Utility
/*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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 1

Expert Comment

by:marvinm
Comment Utility
yeah, what ozo said
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
ozo, what happens when you want to put a breakpoint in one of the Action() funcs?
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
In such cases I might set up only *strings[] and PFUNC funcs[] that way.
0
 
LVL 11

Expert Comment

by:alexo
Comment Utility
Incidently, the current issue of CUJ suggests a similar technique:
    http://www.cuj.com/current/qa.html
0
 
LVL 1

Expert Comment

by:newexpert
Comment Utility
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
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
 
LVL 11

Expert Comment

by:alexo
Comment Utility
newexpert, an interesting idea.  Works even better with bsearch() if the data is sorted.

0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now