Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!bloom-beacon!gatech!mcnc!rti!xyzzy!throopw From: throopw@xyzzy.UUCP (Wayne A. Throop) Newsgroups: comp.lang.c Subject: Re: Variable function names Message-ID: <434@xyzzy.UUCP> Date: Tue, 8-Dec-87 13:09:50 EST Article-I.D.: xyzzy.434 Posted: Tue Dec 8 13:09:50 1987 Date-Received: Sun, 13-Dec-87 12:28:07 EST References: <973@russell.STANFORD.EDU> Organization: Data General, RTP NC. Lines: 57 > rustcat@russell.STANFORD.EDU (Vallury Prabhakar) > Is there an equivalent in C for the "funcall" utility (in Lisp)? Not in general, but in the example below, there is hope. Something to keep in mind if you already know LISP and are trying to learn C: use pointers. The things that LISP does naturally and easily often correspond to the use of pointers. The problem posed is a case in point: > I would like to have a portion of code, that compares a specific string > with a predefined string, and if true, then call the corresponding function. > { > static char *LIST = {"First", "Second", "Third"}; > int First(), Second(), Third(), > int i; > > for (i = 0; i < 3; i ++) { > if (strcmp (, LIST[i]) == 0) { > (...statement that can call the corresponding routine...) > } > } > } Easy enough. You can either have a "parallel" array of pointers to your funcitons, or (more to my taste) you can have a list of name-function "dotted pairs" (well, not really dotted pairs, but a struct with two "cells", much like a cons, but I digress), like so: int invoke_named_function( name ) char *name; { int strcmp(); int First(), Second(), Third(); static struct { char *name; int (*function)(); } table[] = { { "First", First }, { "Second", Second }, { "Third", Third } }; int i; for( i=0; i<(sizeof(table)/sizeof(table[0])); ++i ){ if( strcmp( name, table[i].name ) == 0 ){ return( (*(table[i].function))() ); } } return( -1 ); /* or some other error indication */ } You can simply add as many entries to the table as you like. Note that the (*(table[i].function))() used to invoke the function can in some compilers be replaced by a simple table[i].function(). -- Everyone I know is having a more productive crisis than I am. --- Cathy -- Wayne Throop !mcnc!rti!xyzzy!throopw