Which is better ?

closed account (DEhqDjzh)
Let's say I have aGame class which has gameloop function. What I want to ask is it better to disable gameloop function and copy paste the context to the main file?
So is it better to do like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void Game::gameloop()
{
if(pressed_A)
move_left();
if(pressed_S)
move_down();
if(pressed_D)
move_right();
if(pressed_W)
move_up();




}

main.cpp:
1
2
3
4
5
6
7
8
9
10
Game g;
int main()
{
while(1)
{
g.gameloop();
}


}

Or this 2. method:
main.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Game g;
int main()
{
while(1)
{
if(g.pressed_A)
g.move_left();
if(g.pressed_S)
g.move_down();
if(g.pressed_D)
g.move_right();
if(g.pressed_W)
g.move_up();


}


}

Note: the "better" means: more professional, more easy to read, more easy to debug...
Last edited on
Functions should be your friends, try to keep main() fairly small.

Note: the "better" means: more professional, more easy to read, more easy to debug...

I would say looking at the code you posted, "better" should mean using a consistent indent style (no indentation is not an indent style), that would probably the best way you could improve either snippet.

better to have the function. the compiler can see to inline this function, but you can give it a hint with the inline keyword if you want.

for efficiency, better to have some elses and combined logic though. consider:

void Game::gameloop()
{
//optional: is there a quick test to see if nothing to do and stop here?
if(pressed_W) //in most games this is the most likely input 75% of the time, is it for yours?
move_up();
else if(pressed_S) //is this second most likely?
move_down();
else if(pressed_A)
move_left();
else if(pressed_D)
move_right();
}

why? This bypasses the extra conditional tests once it finds which one to do.
why not? is it possible you have queued up multiple inputs and need to process more than one input per loop? If so, the elses are bad.

why is the function version 'better'? I assume that your code will grow in complexity and that while(1) loop will do more than just this one small block of code. If so, eventually you will have either

A:
while(1) {
gameloop();
graphicsloop();
soundloop();
menuloop();
otherloop();

or
B:
while(1)
{
if(g.pressed_A)
g.move_left();
if(g.pressed_S)
g.move_down();
if(g.pressed_D)
g.move_right();
if(g.pressed_W)
g.move_up();
redrawbuffer()
swapbuffers()
bitblt()
if(sound_on)
playsounds()
if(mouse_move)
getmousepos()
if mouseclick == file_save
savegame()
else if mouseclick == exit
...
well you get the idea.


Last edited on
closed account (DEhqDjzh)
Thanks, @jonnin I usually close this topic after a great answer like that but this time I am not going to because I want to read different opinions and answers
Topic archived. No new replies allowed.