Search code examples
c++sdl-2mainloop

Main loop doesn't exit SDL2, C++


I'm trying to do a very basic main loop with SDL2 but the window opens and I can't close it.

I've written this code:

bool open = true;
    while (open = true) 
  {
       SDL_Event event;
      while (SDL_PollEvent(&event) != 0)
       {  
        if (event.type == SDL_QUIT)
            {
     
            open = false;
            }
       }

   
     }

This opens a window, but I can't close it when I click on the cross to exit.

I've replaced this code with this one, found online:

while (true)
{
  // Get the next event
  SDL_Event event;
  if (SDL_PollEvent(&event))
  {
    if (event.type == SDL_QUIT)
    {
      // Break out of the loop on quit
      break;
    }
  } 

And this works, but I don't understand why my code doesn't run correctly.


Solution

  • You are doing assignment here, making the condition always true:

    while (open = true)
    

    You can use == operator to do comparision, but actually you won't need comparision and you should write simply:

    while (open)