Home > OS >  How to abstract things away in c without having a bunch of function parameters?
How to abstract things away in c without having a bunch of function parameters?

Time:12-30

I've been messing around with SDL2 in c and was wondering how to abstract code away without using too many function parameters. For example, in a normal gameplay loop there is usually an input, update, render cycle. Ideally, I would like this to be abstracted as possible so I could have functions called "input", "update", "render", in my loop. How could i do this in c without having those functions take a ludicrous amount of parameters? I know that c kind of solves this issue through classes, but I am curious and want to know how to do this in a procedural programming setting.

So far, I can't really think of any way to fix this. I tried looking it up online but only get results for c classes. As mentioned before, I want to stick to c because that is what i am comfortable with right now and would prefer to use.

CodePudding user response:

If you have complex state to transport some between calls, put that in a struct. Pass a pointer to that as the sole argument to your functions, out at least as the first of very few.

That is a very common design pattern on C code.

void inputstep(struct state_t* systemstate);
void updatestep(struct state_t* systemstate);
void renderstep(struct state_t* systemstate, struct opengl_context_t* oglctx);

Note also that it is exactly the same, if not even more (due to less safety about pointers), overhead as having a C class with methods.

this in a functional programming setting.

Well, C is about as far as you get from a purely functional language, so functional programming paradigms only awkwardly translate. Are you sure you didn't mean "procedural"?

In a functional programming mindset, the state you pass into a function would be immutable or discarded after the function, and the function would return a new state; something like

struct mystate_t* mystate;
...
while(1) {
  mystate = inputfunc(mystate);
  mystate = updatefunc(mystate);
  …
}

Only that in a functional setting, you wouldn't re-assign to a variable, and wouldn't have a while loop like that. Essentially, you wouldn't write C.

  • Related