i learning function pointers , came across following code:
#include <iostream> using namespace std; // macro define dummy functions: #define df(n) void n() { \ cout << "function " #n " called ... " << endl; } df(a); df(b); df(c); df(d); df(e); df(f); df(g); void (*func_table[])() = {a, b, c, d, e, f, g}; int main(){ while(1){ cout << "press key 'a' 'g' " "or q quit"<< endl; char c, cr; cin.get(c); cin.get(cr); // second 1 cr if ( c == 'q') break; if (c < 'a' || c > 'g') continue; (*func_table[c-'a'])(); } }
can please explain me how pointer function func_table works? in particular effect of having a,b,c,d,e,f,g inside {}
, whole expression doing?
usually when see pointer function initialize pointer assigning function name, in example provided array of characters. how know call df(char)?
also, not sure why needed have statements:
df(a); df(b); df(c); df(d); df(e); df(f); df(g);
also, statement: (*func_table[c-'a'])();
reason why subtracting 'a' because different determine correct letter choose array {a,b,c,d,e,f,g}
?
that ugly, obfuscated code, it's not shame confuses you. let's piece piece:
// macro define dummy functions: #define df(n) void n() { \ cout << "function " #n " called ... " << endl; } df(a);
if expand macro invocation, get:
void a() { cout << "function called ... " << endl; }
and similar b, c , on. a
through g
functions printing own name, nothing more.
void (*func_table[])() = {a, b, c, d, e, f, g};
that's easier read typedef:
typedef void (*funcptr)(); //funcptr function pointer functions of type void x(); funcptr func_table[] = {a, b, c, d, e, f, g};
and actually, {&a, &b, &c, &d, &e, &f, &g}
- author makes use of implicit function-to-function-pointer conversion. meaning: func_table
array of function pointers a
through g
int main(){ while(1){ cout << "press key 'a' 'g' " "or q quit"<< endl; char c, cr; cin.get(c); cin.get(cr); // second 1 cr if ( c == 'q') break; if (c < 'a' || c > 'g') continue;
this should clear. call:
(*func_table[c-'a'])();
c-'a'
offset 'a'
, meaning 0 'a', 1 'b' , on. example, if c 'd', line calls (*func_table['d'-'a'])()
, wich *(func_table[3])()
wich d
- line calls function name typed.
Comments
Post a Comment