#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;
}
}
|
|||||
|
I do like the idea but I'm not sure to really get the benefit of your code compared to (my C is a bit rusty so the code might not be correct) :
Indeed, the code doesn't really seem easier to read but it's definitly harder to check when something wrong's happening. On top of that, the way you use brackets impose the fact that we have one BREAK per CASE/DEFAULT and this limits the expressiveness of your syntax. For instance, we don't have the following cool structures possible with a real switch :
or
or
I'm not quite sure about the kind of feedback you expected so I hope this answers your question. As a side note, I'd choose a different variable name, maybe using |
|||
|
Note that your
And as far as I know it's common practice to wrap macro arguments (i.e |
||||
|
As others have pointed, out never try to re-invent the C language. It makes the code less readable and more error-prone, for no obvious benefits. Function-like macros in general are incredibly error-prone and dangerous (and a pain to debug), they should be avoided. If you for some reason need to use function-like macros, you need to make them safe, properly encapsulate them with braces and parenthesis. In addition, doing strcmp after strcmp in sequence like this, is very slow and inefficient, growing more inefficient with each "case" you add. This is unacceptable if program speed and random access are important. So as for code review, I'd strongly recommend to forget this whole program as quickly as possible, nothing good will come out of it. The proper way to write an algorithm that stores unknown, initially unsorted and completely random input strings, is to use a hash table. |
|||
|
I'd add another vote for "don't do this", you (or another) will suffer having to reread/debug it. I'd try something along the lines of:
Which is just another version of ony's answer. Slightly simpler (maybe), but either version will need keeping in step. |
|||
|