Reputation: 23
I am a beginner with C and programming in general (I have been programming with C/C++ for two years now), and the only types of programs I have ever made were command line math processors which take arguments and do operations on them. There is no forking of what is to be done based off of what the input is. I don't know how to do something like that, so what I have been doing recently is designing my programs in a way that is like:
printf("What feature to use?");
int response;
scanf("%d", response);
if (response == 1)
{
feature01();
}
if (response == 2)
{
feature02();
}
... and I continue on like this. For my programs with usually less than 10 unique features, this is OK, but only for the time being. If I ever wrote a program with 50-100 unique branch features, there might be an issue. How can you process input and branch to different features without using the if statement in the fashion above?
Upvotes: 2
Views: 80
Reputation: 7899
You can create a function table. First, a typedef
typedef void (*feature)();
feature
now stands for a pointer to a function that takes no arguments and returns void
.
Now, write (and notice the index change)
void feature0() {...}
void feature1() {...}
// ...
void feature9() {...}
And then put these into an array:
feature[] actions = {&feature0, &feature1, ..., &feature9};
And then your code becomes (error checking left out):
printf("What feature to use?");
int response;
scanf("%d", &response);
actions[response]();
Pointers to functions get treated as the actual functions when called.
Upvotes: 2
Reputation: 1074475
You can replace a series of if
statements on mutually-exclusive values with switch
in many situations:
switch (response)
{
case 1:
feature01();
break;
case 2:
feature02();
break;
default:
featureXX();
break;
}
That's roughly equivalent to:
if (response == 1)
{
feature01();
}
else if (response == 2)
{
feature02();
}
else
{
featureXX();
}
...except that the compiler can optimize the switch
a bit more.
Upvotes: 3