Basic and Advance C Question:

Download Job Interview Questions and Answers PDF

Is there a way to switch on strings?

C Programming Interview Question
C Programming Interview Question

Answer:

Not directly. Sometimes, it's appropriate to use a separate function to map strings to integer codes, and then switch on those:
#define CODE_APPLE 1
#define CODE_ORANGE 2
#define CODE_NONE 0

switch(classifyfunc(string)) {
case CODE_APPLE:
...

case CODE_ORANGE:
...

case CODE_NONE:
...
}

where classifyfunc looks something like

static struct lookuptab {
char *string;
int code;
} tab[] = {
{"apple", CODE_APPLE},
{"orange", CODE_ORANGE},
};

classifyfunc(char *string)
{
int i;
for(i = 0; i < sizeof(tab) / sizeof(tab[0]); i++)
if(strcmp(tab[i].string, string) == 0)
return tab[i].code;

return CODE_NONE;
}

Otherwise, of course, you can fall back on a conventional if/else chain:

if(strcmp(string, "apple") == 0) {
...
} else if(strcmp(string, "orange") == 0) {
...
}

Download C Programming Interview Questions And Answers PDF

Previous QuestionNext Question
Is there a way to have non-constant case labels (i.e. ranges or arbitrary expressions)?Which is more efficient, a switch statement or an if else chain?