0

This is the example given on the wiki and the way every tutorial I've seen does it...

while (1) {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
        /* handle your event here */
    }
    /* do some other stuff here -- draw your app, etc. */
    }

If I have this kind of event loop within an update function within my game loop, am I wrong in thinking the program is re-defining and re-allocating a place for a new event struct every iteration of the loop? And am I wrong in thinking that's a inefficient way of doing it? Can't the event struct be defined once elsewhere and filled with different events throughout the life of the program without needing totally redefined every iteration of the update function? And if so where would I want the event struct to be defined? Globally within my game or main source file or what?

What would be the benefit, if any, of having the event allocated on heap?

Nick B
  • 3
  • 2
  • 1
    Attributed to [Donald Knuth](https://st]ackify.com/premature-optimization-evil/): "The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.” This is a great example :) Yes, the compiler will allocate a new struct each loop iteration (from the stack). No - there is no real "inefficiency" in doing so :) – paulsm4 Oct 22 '20 at 21:05
  • Thanks a lot, yeah I'm probably worrying too much about making sure I'm doing everything in the absolute most efficient way when I'm still such a beginner. – Nick B Oct 22 '20 at 21:08

1 Answers1

4

First, the variable event is declared on the stack, this costs basically nothing. Since it is a POD type, there is no constructor and/or destructor that has to be run. Also, the lifetime of the variable ends at the end of the loop iteration, and will start again at the start of the next iteration. The compiler will see that it can reuse the variable between iterations.

G. Sliepen
  • 7,637
  • 1
  • 15
  • 31