Skip to main content
GameDev.net gamedev.net
🔒 Locked

functions

Started by unknownnick Nov 30, 2002 at 12:58 PM 4 replies 300+ views
Original Post
unknownnick
unknownnick
Hi! I''m having one question (and I''ll just get to the point). Let''s say I''m having a few (a lot) actions stored in functions like void Action1() void Action2() void Action3() void Action4() void Action5() void Action6() ... And I would like to call those functions... All I can remember is: int action; cin >> action; if(action==1) Action1(); if(action==2) Action2(); ... and at action 50... we have a lots of actions. So, How can I solve this a little bit easyer (faster).
krez
krez
a switch statement would work
--- krez ([email="krez_AT_optonline_DOT_net"]krez_AT_optonline_DOT_net[/email])
elendil67
elendil67
Here''s something that might work well:

  
// Instead of fifty different actions, you could use one function that takes a parameter (num). The num parameter tells which action you want to do

int Action(int num)
{
// Think of switch and case as a way to do if... thens... when you have a lot of them

switch(num)
{
case 1:
{
// Do action #1 here

}

case 2:
{
// Do action #2 here

}

case 3:
{
// Do action #3 here

}
}
} // end Action(num)


// then you could do something like this

int ActionNumber;

cin >> ActionNumber;

Action(ActionNumber);

That would reduce your source code and make your code more elegant-you have to always strive for elegance.

[code matrix]
When you go homeTell them of us, and say:For your tomorrow,We gave our today.
unknownnick
unknownnick
OK. That could be the thing. Thanks.
Cedric
Cedric
An array of function pointer is probably the best way:

  
//Syntax may be wrong here

void (*(actions[50]))() = {&Action1, &Action2, &Action3, ...};

//Call action 1

(*(actions[1]))();

Cédric

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.