Solved

Switch Statement

Posted on 1998-08-04
13
331 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
ID: 1251951
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
ID: 1251952
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
ID: 1251953
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
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 

Accepted Solution

by:
vardis earned 50 total points
ID: 1251954
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
ID: 1251955
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
ID: 1251956
/*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
 
LVL 1

Expert Comment

by:marvinm
ID: 1251957
yeah, what ozo said
0
 
LVL 11

Expert Comment

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

Expert Comment

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

Expert Comment

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

Expert Comment

by:newexpert
ID: 1251961
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
ID: 1251962
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
ID: 1251963
newexpert, an interesting idea.  Works even better with bsearch() if the data is sorted.

0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
negation in C function 14 153
Arduino EDI - Programming language 3 94
Using ANSI C how to Read a .csv file 10 80
What is sub-make ? 2 60
Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

773 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