home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!tnc!m0013
- From: m0013@tnc.UUCP (ARI JORDON)
- Newsgroups: rec.games.programmer
- Subject: Re: Goto [variable] in C++ ?
- Message-ID: <1893@tnc.UUCP>
- Date: 29 Dec 92 05:34:18 GMT
- References: <1992Dec28.144429.1427@jupiter.sun.csd.unb.ca>
- Reply-To: m0013@tnc.UUCP (ARI JORDON)
- Distribution: rec.games.programmer
- Organization: The Next Challenge, Fairfax, Va.
- Lines: 47
-
- In article <1992Dec28.144429.1427@jupiter.sun.csd.unb.ca> kinsman@jupiter.sun.csd.unb.ca (Aphoriel/Kinsman) writes:
- >This is a question from someone new to C...
- >
- >How could I set up C code so that a program goes to a function where the name
- >of the function is placed in a string variable? The specific use I'm thinking
- >of is for an adventure game, where the function the parser calls depends on
- >the verb the player used in typing in his command.. I could set it up as:
- >
- >-If verb_parsed is 'eat' then call eat_function
- >-If verb_parsed is 'give' then call give_function
- >
- >and so forth, but this is awful... How could I write it in C to look like:
- >
- >-Go to [verb_parsed + string_holding_parameter_characters]
- >
- >Like that.
- >
- >Thanks in advance,
- >-Sean Givan / Aphoriel/Kinsman
-
-
- hurm, well, perhaps the simplest way (assuming all your functions take
- the same parameters) is something like this:
-
- typedef int (*FuncPtr)();
-
- FuncPtr arrayOfFunctions[] = {func1, func2, func3...};
-
- /* code to set i to the proper index of the function you want */
-
- FuncPtr f;
- f = arrayOfFunctions[i];
- f(/* params, if any */);
-
- i've seen this used most commonly for programs that have a variable
- function that is decided by the user (such as a program to graph y =
- f(x) where the user choses f from a list). you can use a structure,
- one element of which is a string (the key for looking up the
- function), the other of which is your function pointer.
-
- note: you can cheat, and use functions that don't all take the same
- paramaters, but be careful, and make sure you're passing the right
- number to the function...
-
- --
- The Next Challenge - Public Access Unix in Northern Va. - Washington D.C.
- 703-803-0391 To log in for trial and account info.
-