>> Oh, and....how are pointers to functions useful, too?
I think he's talking about function pointers, dougdbug
Function pointers are nice if you want to avoid a bunch of branching statements, i.e.:
Code:
//Very annoying:
switch(state)
{
case INIT_STATE:
doFunction1();
break;
case RUN_STATE_1:
doFunction2();
break;
case RUN_STATE_2:
doFunction3();
break;
//etc..
}
void doFunction1()
{
//do something
state = RUN_STATE_1;
}
You can replace this with:
Code:
void (*stateFunction)(void); //declared somewhere, modified by various functions
stateFunction = &doFunction1;
stateFunction();
-----
void doFunction1()
{
//do something
stateFunction = &doFunction2;
}
In this example you'll improve efficiency too, because you'll have eliminated a branching statement. Of course I rarely do something like this, but it's something you can do. Another example is callback routines - you might want to specify, when something happens you want a certain function to be called. Well, you'd just set a function pointer to the function you want, and the function you specified would be called when that something happens. This is especially useful for applications like scripting engines:
Code:
typedef void (*funcPtr)();
map<string, funcPtr> funcMap;
funcMap["attack"] = &attack;
funcMap["jump"] = &jump;
...
string cmd;
getline(cin, cmd);
map<string, funcPtr>::iterator it = funcMap.find(cmd);
if(it != funcMap.end())
(it->second)();
Something along those lines.