1
\$\begingroup\$

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)

asked Apr 17, 2016 at 11:15
\$\endgroup\$
1
  • 2
    \$\begingroup\$ You cannot switch over strings in C so the question whether doing so would be better is somewhat moot. \$\endgroup\$ Commented Apr 17, 2016 at 12:03

1 Answer 1

1
\$\begingroup\$

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).

answered Apr 17, 2016 at 11:34
\$\endgroup\$
2
  • 2
    \$\begingroup\$ The code is in C, so switch can't be used on strings, c.f. this SO post for some ideas around it. \$\endgroup\$ Commented Apr 17, 2016 at 12:44
  • \$\begingroup\$ Ow, that's right. \$\endgroup\$ Commented Apr 17, 2016 at 18:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.