Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!olivea!orc!inews!hopi!bhoughto From: bhoughto@hopi.intel.com (Blair P. Houghton) Newsgroups: comp.lang.c Subject: Re: strings as functions Keywords: strings pointers functions Message-ID: <1638@inews.intel.com> Date: 7 Jan 91 16:48:46 GMT References: Sender: news@inews.intel.com Organization: Intel Corp, Chandler, AZ Lines: 58 In article 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."