0

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.

John
  • 3
  • 2
  • 2
    `while (open = true)` is a bug. Its a assignment. You set open to true then check if its true. Use == for comparison – drescherjm Jun 28 '21 at 15:12
  • 2
    Turn on more warning when compiling. Most C++ compilers I've tried warns about this. [example](https://godbolt.org/z/zqjPdW5TY) – Ted Lyngmo Jun 28 '21 at 15:14
  • 1
    I'd also question what is the point of the nested `while`s. – Blindy Jun 28 '21 at 15:24

1 Answers1

2

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)
MikeCAT
  • 73,922
  • 11
  • 45
  • 70