I am new to coding and started off with C. I am trying to recreate the famous Snake game and currently using the betty style of coding. Apparently global variables are not allowed and so far What I have thought of is passing my variables as function parameters but I'm not into it as it seems a rather bad coding practice. How do I go about it?
I declared my variables that are used in diffrent source files as global variables in a header files. so far its working but betty does not allow the use of global variables
Pure functions, that is functions which result only depends on it's arguments (and the same input result in the same output), leads to a program that is easy to reason about and by extension test. This is a good thing to strive towards. It's usually considered good style to keep the number of arguments reasonable. You do that by decomposing large functions into smaller ones that does one thing, and by grouping related variables into struct
(s) that you can easily pass around:
enum direction { UP, RIGHT, DOWN, LEFT };
struct position {
unsigned x;
unsigned y;
};
struct state {
enum direction dir;
struct position pos;
};
void update(struct state *s) {
if(s->dir == UP)
s->pos.y--;
// ...
}
Another option might be to make your global variables static
so they can only be accessed in a given file.
If you are the chaotic evil type then what is worse than global variables is external state: files, database or external services in general. The life time of your data now exceeds the program, and your data may be accessed by other programs possible concurrently with your program.