Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Switch Statements and Branch Tables

Name: Anonymous 2012-04-10 13:55

So let's say I'm making a game, and each monster in it follows a separate movement pattern. For each step of gameplay, each monster must have its movement routine called. Instead of evaluating a conditional to determine which movement pattern a monster should use, I could solve this problem easily by enumerating the movement patterns, and using this value as an index into a jump table.

My first instinct would be to write this (in C) literally as an array of function pointers. The end result would look something like:
for all monsters
    *(movfunctions + monster.movementpattern)(&monster) // call a movement pattern function


Alternatively, I could write a single movement function with a massive switch statement instead:
case MONSTER_KNIGHT: // MONSTER_KNIGHT being #define'd to a constant
    // chase the player
    break;
case MONSTER_BUG:
    // hug the walls
    break;


Now, I get that the entire purpose of a switch statement is to facilitate the creation of jump tables. Could I then assume that the compiled results of both methods would be similar?

Name: Anonymous 2012-04-18 16:36

you can use

patterns[monster.mov_pattern](*monster);

where

void func1(monster * m);
void (*patterns[])(monster *) = {func1, func2, ...};

looks healthy I think

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List