Is there a way to switch on strings?
Submitted by: AdministratorNot 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) {
...
}
Submitted by: Administrator
#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) {
...
}
Submitted by: Administrator
Read Online C Programming Job Interview Questions And Answers
Top C Programming Questions
☺ | Why does this code crash? |
☺ | What is wrong with this declaration? |
☺ | How can I read/write structures from/to data files? |
☺ | What does static variable mean in c? |
☺ | How can I increase the allowable number of simultaneously open files? |
Top Coding/Programming Categories
☺ | Python Interview Questions. |
☺ | OOP Interview Questions. |
☺ | Software engineering Interview Questions. |
☺ | PHP Interview Questions. |
☺ | VBA (Visual Basic for Applications) Interview Questions. |