I've read about various tricks to simulate switch-ing on strings in C/C++.

Here is a hand-rolled method that I'd like to try to figure out how to do with a pre-processor or templates.

The C preprocessor would have the big advantage of being usable in C.

/*
  switch on strings
  e.g.
  int foo(const char* str)
  {
    int ret = 0;
    switch (str)
    {
      case "help":
        ret = 4;
        break;
      case "run":
        ret = 3;
        break;
      default:
        break;
    }
    return ret;
  }
*/

#include <stdio.h>

int foo(const char* str)
{
  int ret = 0;
  int match = 0;
  if (str)
  {
    switch (str[0])
    {
      case 'h':
        ret++;
        switch (str[1])
        {
          case 'e':
          ret++;
          switch (str[2])
          {
            case 'l':
            ret++;
            switch(str[3])
            {
              case 'p':
              {
                ret++;
                switch (str[4])
                {
                  case '\0':
                  match=1; // exactly "help" (case-sensitive)
                }
              }
            }
          }
        }
        break;
      case 'r':
        ret++;
        switch (str[1])
        {
          case 'u':
          ret++;
          switch(str[2])
          {
            case 'n':
            {
              ret++;
              switch(str[3])
              {
                case '\0':
                match=1;  // exactly "run"
              }
            }
          }
        }
      }
    }
  }
  if ( match )
    return ret;
  else
    return 0;
}

int main(int argc, char* argv[])
{
  int r;
  if ( argc > 1 )
    r = foo(argv[1]);

  printf("r=%d\n", r);
  return 0;
}
changed December 21, 2010