Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've written a small C function to handle the builtin commands of a custom shell that I'm writing in C. Is it better to use a switch instead?

int handleBuiltinCommands(char *input, int ret) {
    int built_in_command = 0;
    if (strcmp(input, "exit") == 0) {
        free(input);
        exit(0);
    }
    if (StartsWith(input, "cd")) {
        built_in_command = 1;
        runcd(input);
    }
    if (StartsWith(input, "checkEnv")) {
        built_in_command = 1;
        checkEnv(ret);
    }
    return built_in_command;
}

I compile it with gcc -pedantic -Wall -ansi -O3

(Background: Tokenizing a shell command)

share|improve this question
1  
You cannot switch over strings in C so the question whether doing so would be better is somewhat moot. – 5gon12eder Apr 17 at 12:03
up vote 1 down vote accepted

It's OK to use the if construction, although if you plan to have more than a few commands, using switch leads to cleaner code imho. In addition, why not using if else instead of just if? That way not all of your if have to be evaluated (in average).

share|improve this answer
2  
The code is in C, so switch can't be used on strings, c.f. this SO post for some ideas around it. – ferada Apr 17 at 12:44
    
Ow, that's right. – Enrique Marcos Apr 17 at 18:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.