The use of bitwise operators for window flags is related to how SDL stores multiple configuration options efficiently in a single integer. Let's explore why this works:
Each flag is represented by a single bit in an integer:
#include <SDL.h>
#include <iostream>
#include <bitset>
int main() {
// Let's look at the actual bits of
// some window flags
std::cout << "\nFullscreen: "
<< std::bitset<32>(SDL_WINDOW_FULLSCREEN);
std::cout << "\nBorderless: "
<< std::bitset<32>(SDL_WINDOW_BORDERLESS);
std::cout << "\nResizable: "
<< std::bitset<32>(SDL_WINDOW_RESIZABLE);
}
Fullscreen: 00000000000000000000000000000001
Borderless: 00000000000000000000000000010000
Resizable: 00000000000000000000000000100000
When we want multiple flags, we use the bitwise OR operator (|
) to set multiple bits:
#include <SDL.h>
#include <iostream>
#include <bitset>
int main() {
auto Flags{
SDL_WindowFlags(
SDL_WINDOW_BORDERLESS |
SDL_WINDOW_RESIZABLE
)};
std::cout << "Combined: "
<< std::bitset<32>(Flags);
}
Combined: 00000000000000000000000000110000
If we used the logical OR operator (||
)Â instead:
#include <SDL.h>
#include <iostream>
#include <bitset>
int main() {
auto Flags{
SDL_WindowFlags(
SDL_WINDOW_BORDERLESS ||
SDL_WINDOW_RESIZABLE
)};
std::cout << "Combined: "
<< std::bitset<32>(Flags);
}
Bad Combo: 00000000000000000000000000000001
The logical operator would just give us 1
(true
) or 0
(false
), losing the ability to store multiple flags!
Similarly, we use the bitwise AND operator (&
) to check if specific bits are set:
#include <SDL.h>
#include <iostream>
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* Window{SDL_CreateWindow(
"Flag Example",
100, 200, 600, 300,
SDL_WINDOW_BORDERLESS | SDL_WINDOW_RESIZABLE
)};
auto Flags{SDL_WindowFlags(
SDL_GetWindowFlags(Window))};
// Correct way to check flags
bool HasBorder{!(Flags & SDL_WINDOW_BORDERLESS)};
// Wrong way - would just check if either
// value is non-zero
bool BadCheck{Flags && SDL_WINDOW_BORDERLESS};
std::cout << "Has Border: " << HasBorder;
std::cout << "\nBad Check: " << BadCheck;
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
This bit manipulation approach is very memory efficient and fast, which is why it's commonly used in systems programming and game development.
Answers to questions are automatically generated and may not have been reviewed.
Explore window creation, configuration, and event handling using SDL's windowing system