The other day, I tried to code a little C ++ programming using the SDL multimedia library, and I ran into this little problem, which I eventually resolved through trial and error. The problem is that I understand what I did to solve the problem, but I do not really understand the essence of the problem!
The problem was handling keyboard events in the SDL. The code for processing a single keystroke to exit the program is simple and simple. [eventQueue - structure SDL_Event]
//checks for keypress events.. if ( eventQueue.type == SDL_KEYDOWN ) { //note: uses the boolean logical '==' equals operator.. if ( eventQueue.key.keysym.sym == SDLK_ESCAPE ) { running = false; } }
In the above code, just pressing the ESCAPE key at its ends completes the main loop and forces the program to clear and close ...
However ... The code needed to handle keystrokes that use modifier keys (shift / alt / ctrl) does not work correctly with the '==' operator. It took me a long time to figure out that I needed to use the bitwise AND operator instead of the equality operator (logical?).
//checks for keypress events.. if ( eventQueue.type == SDL_KEYDOWN ) { //note: requires the use of the bitwise AND operator.. if (( eventQueue.key.keysym.mod & KMOD_ALT ) && (eventQueue.key.keysym.sym == SDLK_F4 )) { running = false; } }
My confusion here arises from the fact that when using the "keysym.sym" member, the boolean operator "==" works fine, however, when using the "keysym.mod" member, it was necessary to use the & bitwise AND operator.
Now, if I were to guess, I would say that it has something to do with the fact that "keysym.sym" should only process one numeric value, which is one key on the keyboard, and "keysym". mod 'has to deal with various key combinations shift, ctrl and alt ...?
To summarize my question: Why is this so? Do I need to learn at all, except trial and error, do I need to compare some of the data with bitwise or logical / equality operators? Why does "keysym.sym == SDLK_F4" work fine, but "keysym.mod == KMOD_ALT" doesn't? Why does an operation involving decimal numbers have a different result than an operation that compares the values of bits? Are there also situations where the operation of logical operations and bitwise operations will not work?