home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / rec / games / programm / 5213 < prev    next >
Encoding:
Internet Message Format  |  1992-12-29  |  2.1 KB

  1. Path: sparky!uunet!tnc!m0013
  2. From: m0013@tnc.UUCP (ARI JORDON)
  3. Newsgroups: rec.games.programmer
  4. Subject: Re: Goto [variable] in C++ ?
  5. Message-ID: <1893@tnc.UUCP>
  6. Date: 29 Dec 92 05:34:18 GMT
  7. References: <1992Dec28.144429.1427@jupiter.sun.csd.unb.ca>
  8. Reply-To: m0013@tnc.UUCP (ARI JORDON)
  9. Distribution: rec.games.programmer
  10. Organization: The Next Challenge, Fairfax, Va.
  11. Lines: 47
  12.  
  13. In article <1992Dec28.144429.1427@jupiter.sun.csd.unb.ca> kinsman@jupiter.sun.csd.unb.ca (Aphoriel/Kinsman) writes:
  14. >This is a question from someone new to C...
  15. >
  16. >How could I set up C code so that a program goes to a function where the name
  17. >of the function is placed in a string variable? The specific use I'm thinking
  18. >of is for an adventure game, where the function the parser calls depends on
  19. >the verb the player used in typing in his command.. I could set it up as:
  20. >
  21. >-If verb_parsed is 'eat' then call eat_function
  22. >-If verb_parsed is 'give' then call give_function
  23. >
  24. >and so forth, but this is awful... How could I write it in C to look like:
  25. >
  26. >-Go to [verb_parsed + string_holding_parameter_characters]
  27. >
  28. >Like that.
  29. >
  30. >Thanks in advance,
  31. >-Sean Givan / Aphoriel/Kinsman
  32.  
  33.  
  34. hurm, well, perhaps the simplest way (assuming all your functions take
  35. the same parameters) is something like this:
  36.  
  37. typedef int (*FuncPtr)();
  38.  
  39. FuncPtr arrayOfFunctions[] = {func1, func2, func3...};
  40.  
  41. /* code to set i to the proper index of the function you want */
  42.  
  43. FuncPtr f;
  44. f = arrayOfFunctions[i];
  45. f(/* params, if any */);
  46.  
  47. i've seen this used most commonly for programs that have a variable
  48. function that is decided by the user (such as a program to graph y =
  49. f(x) where the user choses f from a list).  you can use a structure,
  50. one element of which is a string (the key for looking up the
  51. function), the other of which is your function pointer.
  52.  
  53. note: you can cheat, and use functions that don't all take the same
  54. paramaters, but be careful, and make sure you're passing the right
  55. number to the function...
  56.  
  57. -- 
  58. The Next Challenge - Public Access Unix in Northern Va. - Washington D.C.
  59. 703-803-0391 To log in for trial and account info.
  60.