'static const int keys", why are you using a constant here? |
It's a lookup table. This allows you to keep all the keys you want to check in a single array. This lets you avoid copy/pasting blocks of code over and over for each key. Plus, if you want to add/remove keys later, all you have to do is change that array.
And what does the 'static' mean? |
It's a style/performance thing.
static local variables are allocated once on first use and have a lifetime that persists throughout the life of the program.
Whereas non-static variables are allocated and initialized each and every time the function is called.
By making the constant array static, it'll only get initialized once rather than multiple times.
Functionally, the code will be the same regardless of whether or not you have static there, so it doesn't really matter. It's just an old habit of mine, really.
for(auto key : keys) - what does this do? I know how for functions, but I don't understand the command inside it |
This is a range-based for loop, introduced in C++11.
for(auto key : keys)
loops for each element in the 'keys' container... and 'key' will be the current element inside that loop.
This loop:
1 2 3 4 5
|
for(auto key : keys)
{
if(GetAsyncKeyState(key) & 0x8000)
keypressed = key; // this key is pressed!
}
|
Is exactly the same as this loop:
1 2 3 4 5
|
for(int i = 0; i < 4; ++i)
{
if(GetAsyncKeyState(keys[i]) & 0x8000)
keypressed = keys[i]; // this key is pressed!
}
|
The only differences are the first loop...
1) ...is more succinct.
2) ...doesn't need to know the size of the 'keys' array (notice how I had to hardcode in '4' in the 2nd loop).
and lastly, what is the ' & 0x8000' , why is it needed? |
& 0x8000 masks out and isolates bit 15 from the returned value.
GetAsyncKeyState doesn't only give you the up/down state of the key... it actually gives you a few different pieces of info about the key. Since the only thing we're interested in is up/down state... I isolate that bit and force all other bits to zero.