0

Based on an answer of the following question: How do I transform an IF statement with 2 variables onto a switch function using C?

I want to develop SWITCH and CASE macros to use it (like switch and case) for strings.

Some thing like that:

char buf[256];

SWITCH (buf) {
    CASE ("abcdef"):
        printf ("A1!\n");
        BREAK;
    CASE ("ghijkl"):
        printf ("B1!\n");
        BREAK;
    DEFAULT:
        printf ("D1!\n");
        BREAK;
}

what could be SWITCH and CASE and BREAK and DEFAULT here ?

Community
  • 1
  • 1
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • That's not really a `switch` heh. I don't see why someone would want to do that: there's nothing wrong with using `if...else if...else` here, and it doesn't rely on some shady preprocessor directive. – netcoder Jan 07 '13 at 17:14
  • nothing wrong with if..else if. Just a way of writing my code. to be more readeble – MOHAMED Jan 07 '13 at 17:16
  • It's not more readable when it is confusing everyone else. – Bo Persson Jan 07 '13 at 18:02

2 Answers2

2

If you really want it, well, here it is:

#include <string.h>
#include <stdio.h>
const char *kludge;
#define evilmacro(line) label##line
#define fakelabel(line) evilmacro(line)
#define SWITCH(str) while((kludge = (str)))
#define CASE(str) if(strcmp(kludge, str) == 0) { fakelabel(__LINE__)
#define BREAK break; /* out of while loop */ }
#define DEFAULT if(1) { fakelabel(__LINE__)
int main(int argc, char *argv[]) {
SWITCH (argv[1]) {
    CASE ("abcdef"):
        printf ("A1!\n");
        BREAK;
    CASE ("ghijkl"):
        printf ("B1!\n");
        BREAK;
    DEFAULT:
        printf ("D1!\n");
        BREAK;
}
return 0;
}

Getting rid of the unused labels is left as an exercise for the reader :)

EDIT: fwiw, what I would really do is table driven code.

loreb
  • 1,327
  • 1
  • 7
  • 6
-1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SWITCH(S) char *_S = S; if (0)
#define CASE(S) } else if (strcmp(_S, S) == 0) {switch(1) { case 1
#define BREAK }
#define DEFAULT } else {switch(1) { case 1

int main()
{
    char buf[256];

    printf("\nString - Enter your string: ");
    scanf ("%s", buf);

    SWITCH (buf) {
        CASE ("abcdef"):
            printf ("B1!\n");
            BREAK;
        CASE ("ghijkl"):
            printf ("C1!\n");
            BREAK;
        DEFAULT:
            printf ("D1!\n");
            BREAK;
    }
}
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • That breaks badly: `SWITCH (buf) { CASE ("abcdef"): if (1) { BREAK; } printf("boo\n");}` – kmkaplan Jan 07 '13 at 17:03
  • @kmkaplan The question is asking for a particular use and not for general use: "What could be `SWITCH` and `CASE` and `BREAK` and `DEFAULT` **here**" ? – MOHAMED Jan 07 '13 at 17:07