Nexus Archive

SDL Poll Event

Trying out SDL I've went to create a 640x480 window and then pause the window for 5 seconds before destroying the window.

//create a SDL window pointer
SDL_Window* window = nullptr;
window = SDL_CreateWindow(
    "Base SDL Window",
    150,
    150,
    640,
    480,
    SDL_WINDOW_SHOWN
);

//pause the window for 5 sec
SDL_Delay(5000);

//destroy the window
SDL_DestroyWindow(window);
SDL_Quit();

Now adding an infinite loop I can crate a never closing window which eventually crashes (Window is not responding).

bool windowIsRunning = true;
while(windowIsRunning){}

😜 !

Then I land in Event Polling and making my window close when I click the ❌ !

int eventCount = 0;
bool windowIsRunning = true;
while(windowIsRunning){
    SDL_Event event;
    
    //start the event loop
    while(SDL_PollEvent(&event)){
        //handle events
        if(event.type == SDL_QUIT){
            windowIsRunning = false;
        }
        
        eventCount++;
        std::cout << "Event: " << eventCount << ", Event Type: " << event.type << "\n";
    }
}

So based on my understanding, the first is the main loop that runs indefinitely. Next we create a SDL_Event struct object.

The event queue stores any event that has occurred and the SDL_PollEvent() function pops the first event in the queue and stores it in the SDL_Event object that was created and returns 1 and it continues to do so for every event in the queue.

Then a check for the event type of SDL_QUIT is done which then updates our boolean value to stop the main loop and close SDL.

To check for event and its count I logged the event count and type for each event that happens. The event type logged is of type Uint32, so basically a positive integer of 32 bits.


This below is my sort of explanation (I asked Gemini to verify my understanding):

So the outer loops runs creates a SDL_Event object then hits the inner while which calls the polling function and if it returns 0 it doesn't enter the inner while and then this continues forever. Now in case a event does occur it is stored in the SDL event queue and then the as the outer loop is running a SDL_Event object is created but this time the inner loop returns 1 since the queue is not empty this time it enters the inner while and after executing the inner while it then checks the inner while condition again, still valid ? Inner loop runs for n times and once the queue is empty it exits and the outer loop just runs. For an instance i if there are n events in the queue the inner queue runs n times.

Click here for Source Code.


References:

Mike Shah on YouTube

Google Gemini

ChatGPT

#CPP #SDL_Sandbox