Here is another variation on the theme.
Code:
#include <stdio.h>
typedef void (*fpvv)(void);
void foo(void) { puts("foo"); }
void bar(void) { puts("bar"); }
fpvv event_handler(int button)
{
switch ( button )
{
case 4: return foo;
case 6: return bar;
default: break;
}
return NULL;
}
int main(void)
{
int i;
for ( i = 0; i < 10; ++i )
{
fpvv function = event_handler(i);
if ( function )
{
printf("i = %d: ", i);
function();
}
}
return 0;
}
/* my output
i = 4: foo
i = 6: bar
*/
[EDIT]
And as long as I'm messing around with this...
Code:
#include <stdio.h>
#include <string.h>
typedef void (*fpvv)(void);
void up(void) { puts(">> going up"); }
void down(void) { puts(">> going down"); }
void left(void) { puts(">> going left"); }
void right(void) { puts(">> going right"); }
fpvv event_handler(const char *text)
{
static const struct
{
const char *label;
const fpvv function;
} button[] =
{
{ "up", up },
{ "down", down },
{ "left", left },
{ "right", right },
};
size_t i;
for ( i = 0; i < sizeof button / sizeof *button; ++i )
{
if ( strcmp(button[i].label, text) == 0 )
{
return button[i].function;
}
}
return NULL;
}
int main(void)
{
const char *message[] =
{
"hello","help","me","go","up","down","and","to","the",
"left","or","right","please",
};
size_t i;
for ( i = 0; i < sizeof message / sizeof *message; ++i )
{
fpvv function = event_handler(message[i]);
printf("message[%2d] = %-6s : ", (int)i, message[i]);
if ( function )
{
function();
}
else
{
puts("unknown");
}
}
return 0;
}
/* my output
message[ 0] = hello : unknown
message[ 1] = help : unknown
message[ 2] = me : unknown
message[ 3] = go : unknown
message[ 4] = up : >> going up
message[ 5] = down : >> going down
message[ 6] = and : unknown
message[ 7] = to : unknown
message[ 8] = the : unknown
message[ 9] = left : >> going left
message[10] = or : unknown
message[11] = right : >> going right
message[12] = please : unknown
*/
[/EDIT]