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-10 16:19

Could I then assume that the compiled results of both methods would be similar?
No, you can't make any judgments about the compiled code beyond that it upon termination should output the same as the C abstract machine given the same input. At least not until you specify a compiler.

(Besides you can't do arithmetic with function pointer types in C, so you're probably mistaking your favorite compiler for C anyway.)

I would rather store a function pointer in the base structure itself and then create a regular selector function, the end result would look something like.

move_entity(&monster);
and equivalently
move_entity(&hero);

If you really insist on being retarded you can use an enum, using a #define for this is way beyond retarded.

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