Re: function pointers



hifrnds007@xxxxxxxxx wrote in comp.lang.c:
how the function poiners avoids the usage of switch cases?

"Tomás Ó hÉilidhe" <toe@xxxxxxxxxxx> writes:
Here's a typical switch statement:

switch (user_input)
{
case 0: DeleteFile(); break;
case 1: CopyFile(); break;
case 2: RenameFile(); break;
case 4: MoveFile();
}

And here's the function pointer equivalent:

void (*const funcs[4])(void) = {DeleteFile,CopyFile,Renamefile,MoveFile};

funcs[user_input];

Forgot about "()" and to be precise you should check if user_input is >=
0 and <= 4.

Whether that is faster is another matter. Compiler may implement
a switch using an array of locations in program and achieve the same or
even higher speed (no need to call a function, simple jump).

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>--<jid:mina86*jabber.org>--ooO--(_)--Ooo--
.