Does SDL_PollEvent() Permanently Remove Events from the Queue in SDL2?
If SDL_PollEvent() pops an event, does that mean it's gone forever?
Yes, when SDL_PollEvent() successfully retrieves an event from SDL's internal event queue, that specific event instance is permanently removed from the queue.
Understanding Queues and Popping
Think of SDL's event queue like a line of people waiting for service.
- New events arriving from the operating system (via
SDL_PumpEvents()or the internal pumping withinSDL_PollEvent()) are added to the back of the line (queue). SDL_PollEvent()looks at the person at the front of the line.- If someone is there (
SDL_PollEvent()returnstrue), it "serves" that person (copies the event data into theSDL_Eventvariable you provided) and that person leaves the line (the event is removed from the queue). - If the line is empty (
SDL_PollEvent()returnsfalse), nothing happens to the queue.
Event Data vs. Queue Instance
It's helpful to distinguish between the data representing the event and the event's place in the queue.
When SDL_PollEvent(&myEvent) returns true:
- SDL identifies the event structure at the front of its internal queue.
- SDL copies the data from that internal event structure into your
myEventvariable. - SDL then removes the internal event structure from the front of its queue.
Your myEvent variable now holds a copy of the information about the event that was at the front of the queue. The original instance in the queue itself is gone.
SDL_Event currentEvent;
bool shouldContinue{true};
while (shouldContinue) {
// Check the front of the queue
while (SDL_PollEvent(¤tEvent)) {
// If an event was found (SDL_PollEvent returned true):
// 1. currentEvent is now filled with data from that event.
// 2. That specific event is REMOVED from SDL's queue.
if (currentEvent.type == SDL_QUIT) {
// We process the data we received
shouldContinue = false;
// The original SDL_QUIT event instance is gone from the queue.
} else if (currentEvent.type == SDL_KEYDOWN) {
// Process key press based on data in currentEvent
// The original SDL_KEYDOWN event instance is gone.
}
// If we don't handle an event type here, its data in
// currentEvent is overwritten on the next loop iteration
// (if another event exists), and the original event instance
// is still gone from the queue.
}
// ... Update ...
// ... Render ...
}Because SDL_PollEvent() removes the event, it's crucial that your event-handling logic (the code inside the while(SDL_PollEvent(...)) loop) fully processes or makes a decision about each event as it receives it.
If you ignore an event after polling it, you won't get a second chance to retrieve that specific event instance from the queue later - it's gone.
Implementing an Application Loop
Step-by-step guide on creating the SDL2 application and event loops for interactive games