Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
Is there a way to switch on strings?
Is there a way to switch on strings?
✍: Guest
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) {
...
}
2015-02-04, 1351👍, 0💬
Popular Posts:
How To Merge Cells in a Row? - XHTML 1.0 Tutorials - Understanding Tables and Table Cells If you wan...
What are secure and non-secure websites? A secure Website uses the Secure Socket Layer (SSL) protoco...
What is the difference between const char* p and char const* p? In const char* p, the character poin...
How do I force the Dispose method to be called automatically, as clients can forget to call Dispose ...
when should the volatile modifier be used? The volatile modifier is a directive to the compiler's op...