AceFirebird AceFirebird - 9 months ago 57
C Question

Using Structs to hold all my variables in a C game?

I am currently getting into some more advanced C programming with SDL and I've been having a lot of trouble with functions and overall program structure.

My main problem is that games require a lot of variables that most functions need to access and manipulate. I don't want to create a bunch of global variables, but I also don't want to be passing around every single relevant variable each time I access a function.

To solve this, I created a Game struct at the top of the program. This struct holds all of the game variables that needs to be passed around like textures and locations. I declare an instance of that struct at the beginning of my main function, initialize all the variables inside, and then proceed to pass the struct instance around to different functions.

My question is: is this a good solution? Perhaps there is a better, more conventional way to deal with this; if so, please explain.

This is more of a theoretical question and has no grounding in any specific code that I can show you.


This is kind of better... but it's an opinion thing. First, It looks nicer. Second, if you're smart, you can dump the entire game structure to a file for later loading.

Also, you should declare the struct at the top level:

/* main.c */

typedef struct{
    int health;
    int xp_level;
} game_t;

game_t GAME;

main(){ = 42;
    GAME.xp_level = 0;

Hence any functions you write just have acess to the struct without needing to pass it.

You could also use the Ularn approach:

/* Character.h */


#define HP 0    
#define STR 1
#define INT 2
#define WIS 3
/* etc... */