strings as functions

Blair P. Houghton bhoughto at hopi.intel.com
Tue Jan 8 03:48:46 AEST 1991


In article <mpapp.663214690 at godzilla> mpapp@ (Mike Papper) writes:
>Is there a way to use a string value as the name of a function?
>In other words, can I use a string (possibly

Strings is data, and functions is text, and never the twain
will get stuck in the same location.  If, however, you can
get the user a copy of the long-integers that represent the
function pointers, get him/her to type those in, the program
can convert the typed-in number to integral data, then
call-by-reference.  It would work, but it's laughable.

There are easier ways; read on.

>One method may be to call the same function, which uses the value
>of the string to decide which real function to call.

That's the easier way.  It's a very common practice to
build lists of structures that each contain a command-name
(a string) and a pointer to the (already compiled) function
that implements that command.  The user types-in the
string, the program searches the list for a matching
string, and the program calls the associated function via
the function-pointer.

(Note:  look up the difference between function pointers
and object pointers (the sort you're used to); there are
many differences and there are many things you can't do
with a function pointer.)  (Note also:  unless all the
functions return the same type, you'll have to make them
all return nothing; the easy way out of this is to make
them return a (pointer to a) union and have the program
figure out which union-member-tag to use).

>In this case the programmer would have to edit the source code that was 
>generated to match up the strings and the appropriate function calls.

That's what programmers are for.  :-/

>The idea is to have a program that reads an ASCII file to generate
>an interface, which when buttons are selected, the
>appropriate function is called. The function to call
>would be found in the ascii file, and the program would assume
>the programmer had created the function of same name somewhere.

The program doesn't have to assume anything.  When the
search-loop finds a match for the command, simply set a
flag, and after the end of the loop you can check the flag
to see if the search was successful and if not you can
print an error message.

>Can this be done? easily?

Yes.  Virtually every program you've ever used has done something
very similar to this when dealing with interactive/interpreted input;
it's often also the way command-line arguments are handled.

				--Blair
				  "Common == easy; ethologically."



More information about the Comp.lang.c mailing list