'Why does SDL_RenderPresent disable my quit event?

I wrote this program that outputs the coordinate of my current mouse position:

#include <sdl.h>
#include <iostream>

int main (int argc, char** argv) {
    SDL_Init(SDL_INIT_VIDEO);
    bool running = true;
    SDL_Window* window = SDL_CreateWindow("testing cursor", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    while(running) {
        SDL_SetRenderDrawColor(renderer, 20, 205, 244, 255);
        SDL_RenderClear(renderer);
        SDL_RenderPresent(renderer);

        SDL_Event mouse;
        while(SDL_PollEvent(&mouse)){
            switch(mouse.type){
            case SDL_MOUSEMOTION:
                std::cout << mouse.motion.x << " " << mouse.motion.y << '\n';
            }
        }

        SDL_Event quit;
        while(SDL_PollEvent(&quit)){
            switch(quit.type){
            case SDL_QUIT:
                running = false;
                break;
            default:
                break;
            }
        }
    }
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}

However, SDL_RenderPresent renders my SDL_Event quit obsolete for some reasons. That is, if I remove the whole SDL_SetRenderDrawColor then the programs handle the quitting correctly (with no background), but if I leave everything as is then I cannot quit normally.

My IDE of choice is CodeBlock 20.03, with SDL 2 vers 2.0.14.



Solution 1:[1]

The reason is that the first loop pulls all events from the queue, including SDL_QUIT, which you do not handle in it, so this event is always lost. The second loop will never execute because the queue will always be empty at this point.

The solution is to use only one event-processing loop:

#include <sdl.h>
#include <iostream>

int main (int argc, char** argv) {
    SDL_Init(SDL_INIT_VIDEO);
    bool running = true;
    
    SDL_Window* window = SDL_CreateWindow("testing cursor", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, 0);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    
    while(running){
        SDL_SetRenderDrawColor(renderer, 20, 205, 244, 255);
        SDL_RenderClear(renderer);
        SDL_RenderPresent(renderer);

        SDL_Event event;
        
        while(SDL_PollEvent(&event)){
            switch(event.type){
            case SDL_QUIT:
                running = false;
                break;
            case SDL_MOUSEMOTION:
                std::cout << event.motion.x << " " << event.motion.y << '\n';
                break;
            }
        }
    }
    
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();
    
    return 0;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 furious programming