G
Guest
I repeatedly get into the situation where i need to take action
accordingly to input in form of a char*, and have found two manners of
approaching this, i'd appretiate pointers as to which is the best.
The first approach is very small, but is kinda hardwired and gets really
cluttery with many options. The second one takes 3 times as much code, but
is more dynamic and easy to see what it does.
/* Approach #1
* Note that this one generally comes out with more code than
* this out of some reason
*/
void do(char* input) {
if(strcmp(input, "foo") == 0) do_foo();
else if(strcmp(input, "bar") == 0) do_bar();
else if(strcmp(input, "baz") == 0) do_baz();
else do_wtf();
}
/* Approach #2 */
void do(char* input) {
char* commands[] = {"foo", "bar", "baz"};
enum { FOO = 0, BAR, BAZ, MAX };
int cmd = 0;
while(cmd < MAX) if(strcmp(commands[cmd++], input)==0) break;
switch(cmd) {
case FOO: do_foo(); break;
case BAR: do_bar(); break;
case BAZ: do_baz(); break;
default: do_wtf(); break;
}
}
accordingly to input in form of a char*, and have found two manners of
approaching this, i'd appretiate pointers as to which is the best.
The first approach is very small, but is kinda hardwired and gets really
cluttery with many options. The second one takes 3 times as much code, but
is more dynamic and easy to see what it does.
/* Approach #1
* Note that this one generally comes out with more code than
* this out of some reason
*/
void do(char* input) {
if(strcmp(input, "foo") == 0) do_foo();
else if(strcmp(input, "bar") == 0) do_bar();
else if(strcmp(input, "baz") == 0) do_baz();
else do_wtf();
}
/* Approach #2 */
void do(char* input) {
char* commands[] = {"foo", "bar", "baz"};
enum { FOO = 0, BAR, BAZ, MAX };
int cmd = 0;
while(cmd < MAX) if(strcmp(commands[cmd++], input)==0) break;
switch(cmd) {
case FOO: do_foo(); break;
case BAR: do_bar(); break;
case BAZ: do_baz(); break;
default: do_wtf(); break;
}
}