Using Bitwise AND for Flags
Why do we use bitwise AND (&
) for checking flags instead of regular equality (==
)?
Understanding why we use the bitwise AND operator (&
) instead of equality (==
) for checking flags requires understanding how bit flags work in SDL and many other programming contexts.
How Flags Work
Each flag is represented by a single bit in a larger integer. For example:
// These are example values - actual SDL
// values might differ
// Bit 0
const Uint32 FLAG_FULLSCREEN = 0b00000001;
// Bit 1
const Uint32 FLAG_MOUSE_GRABBED = 0b00000010;
// Bit 2
const Uint32 FLAG_BORDERLESS = 0b00000100;
When multiple flags are set, we combine them using bitwise OR (|
):
SDL_Window* Window{SDL_CreateWindow(
"Window Title",
100, 100, 800, 600,
SDL_WINDOW_FULLSCREEN | SDL_WINDOW_MOUSE_GRABBED
)};
Why We Use Bitwise AND
When checking flags, we use &
because:
- A window can have multiple flags set simultaneously
&
checks if specific bits are set, regardless of other bits
Here's an example showing the difference:
#include <SDL.h>
#include <iostream>
void CheckFlags(Uint32 flags) {
// Incorrect way (using ==)
if (flags == SDL_WINDOW_MOUSE_GRABBED) {
std::cout << "This might miss the flag";
}
// Correct way (using &)
if (flags & SDL_WINDOW_MOUSE_GRABBED) {
std::cout << "This correctly detects the flag";
}
}
int main(int argc, char** argv) {
SDL_Init(SDL_INIT_VIDEO);
// Create window with multiple flags
SDL_Window* Window{SDL_CreateWindow(
"Flag Example", 100, 100, 800, 600,
SDL_WINDOW_MOUSE_GRABBED
| SDL_WINDOW_BORDERLESS
)};
Uint32 flags{SDL_GetWindowFlags(Window)};
CheckFlags(flags);
SDL_DestroyWindow(Window);
SDL_Quit();
return 0;
}
This correctly detects the flag!
The equality check fails because:
flags == SDL_WINDOW_MOUSE_GRABBED
checks if ONLY mouse grab is set- But our window has both mouse grab AND borderless flags set
The bitwise AND succeeds because:
flags & SDL_WINDOW_MOUSE_GRABBED
checks if the mouse grab bit is set- It doesn't care about other flags that might also be set
Mouse Input Constraints
Implement mouse constraints in SDL2 to control cursor movement using window grabs and rectangular bounds