The bitwise AND operator (&
) is used with window flags because SDL uses a technique called bit flags to store multiple boolean values in a single integer. Each bit in the flags value represents a different window state.
Here’s an example where we set and check bit flags:
#include <SDL.h>
#include <iostream>
void ExplainFlags() {
// Example flags value where multiple
// states are true
Uint32 Flags{
SDL_WINDOW_FULLSCREEN_DESKTOP |
SDL_WINDOW_SHOWN
};
// Check individual flags
bool IsFullscreen{
(Flags & SDL_WINDOW_FULLSCREEN) != 0
};
bool IsShown{
(Flags & SDL_WINDOW_SHOWN) != 0
};
// Wrong way - this won't work!
bool WrongCheck{Flags == SDL_WINDOW_FULLSCREEN};
std::cout << std::boolalpha
<< "Is fullscreen: " << IsFullscreen
<< "\nIs shown: " << IsShown
<< "\nWrong check: " << WrongCheck;
}
Is fullscreen: true
Is shown: true
Wrong check: false
Using ==
wouldn't work because it checks if the entire flags value exactly matches a single flag. When multiple flags are set (which is common), ==
would return false even when the flag we're interested in is set.
Here's a simplified example showing how bits work:
#include <SDL.h>
#include <bitset>
#include <iostream>
void ShowBitPatterns() {
// For demonstration, using small
// values instead of actual SDL flags
constexpr Uint8 FLAG_A{0b00000001}; // Bit 0
constexpr Uint8 FLAG_B{0b00000010}; // Bit 1
constexpr Uint8 FLAG_C{0b00000100}; // Bit 2
// Set multiple flags
Uint8 Flags{FLAG_A | FLAG_B};
std::cout << "Flag patterns:\n"
<< std::bitset<8>(Flags) << " (All flags)\n"
<< std::bitset<8>(FLAG_A) << " (Flag A)\n"
<< std::bitset<8>(FLAG_B) << " (Flag B)\n"
<< std::bitset<8>(FLAG_C) << " (Flag C)\n\n"
<< "Checking flags:\n"
<< "Has Flag A: " << bool(Flags & FLAG_A)
<< "\nHas Flag B: " << bool(Flags & FLAG_B)
<< "\nHas Flag C: " << bool(Flags & FLAG_C);
}
This pattern allows SDL to efficiently store and check multiple window states using a single integer value.
We cover bit flags and bitwise operators in a dedicated lesson:
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create and manage fullscreen windows in SDL, including desktop and exclusive fullscreen modes.