Mackenzy Brown Mackenzy Brown - 3 months ago 15
C Question

Refactoring if statements when reading keywords from a string

I'm relatively new to programming but have been a long time lurker on SO.

I'm currently studying at university and I'm having a little trouble with writing a program that is essentially a very basic calculator where the input and output are displayed to the user as Hexadecimal.

Most of the code is good to go, but I was wondering if there was a way to refactor this particular code so it doesn't (essentially) just use a large block of if statements to link together the operator the user enters to the it's corresponding function?

This is a snippet of what I've done, and what I need to refactor.

Personally I feel like I should either be nesting or perhaps taking advantage of loops for this, but I don't have enough knowledge to know for sure!

Thanks heaps.

int main() {
printf ("Type in an expression: ");
scanf ("%x %s %x", &a, op, &b);
if (strcmp (op, "add") == 0)
add(a, b);
if (strcmp (op, "sub") == 0)
sub(a, b);
if (strcmp (op, "and") == 0)
band (a, b);
if (strcmp (op, "or") == 0)
bor (a, b);
/* ...... and so on .....*/



You should use else ifs. (If op matches "add" it's most definitely pointless to test if it also matches "or" (etc.).)

The "pro" way to do this kind of parsing is with a lexer (such as flex) and a parser generator (such as bison), which allow you to generate C code that matches all possibilities simultaneously, but those take a little bit of time to learn. For simple stuff, you're good with if else and strcmp.