SDL_PollEvent()
and SDL_WaitEvent()
are two distinct functions for retrieving events from SDL's event queue, differing primarily in their behavior when no events are pending.
SDL_PollEvent()
Behavior: Checks the event queue for pending events.
SDL_Event
structure with the event data and returns 1
(true).0
(false) immediately without waiting.Use Case: This is the standard choice for game loops and real-time applications. Because it doesn't wait, the rest of your game loop (updating game logic, rendering) can execute even if the user isn't providing any input. This prevents the application from freezing.
// Typical game loop structure
SDL_Event e;
bool quit = false;
while (!quit) {
// Handle events currently in the queue
while (SDL_PollEvent(&e)) { // Returns 0 immediately if queue empty
if (e.type == SDL_QUIT) {
quit = true;
}
// Handle other events like mouse motion, clicks, keys...
HandleEvent(e);
}
// Update game state (runs every frame)
UpdateGame();
// Render the scene (runs every frame)
RenderGame();
}
SDL_WaitEvent()
Behavior: Checks the event queue for pending events.
SDL_Event
structure and returns 1
(true).1
. It can optionally time out if SDL_WaitEventTimeout()
is used.Use Case: This is more suitable for applications that don't need to constantly update or render unless there's user input, such as:
SDL_WaitEvent()
allows the application's thread to sleep, consuming fewer resources.// Typical event-driven (non-game loop) structure
SDL_Event e;
bool quit = false;
while (!quit) {
// Waits here until an event happens
if (SDL_WaitEvent(&e)) { // Blocks if queue is empty
if (e.type == SDL_QUIT) {
quit = true;
}
// Handle other events
HandleEventAndUpdateUIIfNeeded(e);
} else {
// SDL_WaitEvent returning 0 usually indicates an error
std::cerr << "Error waiting for event: "
<< SDL_GetError() << '\n';
quit = true; // Exit on error
}
}
Feature | SDL_PollEvent() | SDL_WaitEvent() |
---|---|---|
Queue Empty | Returns 0 immediately | Blocks (waits) until an event arrives |
Return Value | 1 (event), 0 (no event/error) | 1 (event), 0 (error) |
CPU Usage | Higher (loop runs continuously) | Lower (sleeps when idle) |
Primary Use | Game loops, real-time applications | GUI applications, low-resource tools |
Choose SDL_PollEvent()
for applications that need continuous processing and rendering, and SDL_WaitEvent()
for applications that only need to act when the user does something.
Answers to questions are automatically generated and may not have been reviewed.
Discover how to process mouse input, including position tracking and button presses