Global variables and SDL keyboard array

I understand that it's worth avoiding global variables. I had a problem with one that I think I solved, but was wondering if this sort of thing happens...
I had an int variable, WorldPosX declared above the main function. Also a keyboard array:
1
2
int WorldPosX = 0;
bool keys[256];

and something like this to read the keystrokes...
1
2
3
4
5
6
case SDL_KEYDOWN:
   keys[event.key.keysym.sym] = true;
   break;
case SDL_KEYUP:
   keys[event.key.keysym.sym] = false;
   break;

And called to the array as such...
1
2
3
4
if (keys[SDLK_LEFT])
{
...
}

Some of the keyboard buttons were changing my int variable, WorldPosX. Most notable were (left and right control), (left and right shift keys) and one of the alt keys would crash the program. All these keys I was not trying to use.
I moved the int variable, WorldPosX to inside the main function and all the problems stopped.
Can this sort of thing happen?
Thanks,
dpixel
The array is too small. SDLK_RIGHT and SDLK_LEFT has value 275 and 276 respectively. What is happening in your program is that you are writing and reading to memory locations after the array which might overwrite other variables or possibly crash the program.

SDL already stores such an array so there is probably no point in defining and updating your own. You can get a pointer to the array using SDL_GetKeyState. http://www.libsdl.org/cgi/docwiki.fcg/SDL_GetKeyState
1
2
3
4
5
6
7
Uint8* keys = SDL_GetKeyState(NULL);

// You can use keys as you did before.
if (keys[SDLK_LEFT])
{
...
}

Maybe I was thinking RGB..lol

Anyway, problem solved. I changed my array and everything cleared up. And then tried SDL_GetKeyState() and that worked great too without changing anything else.

Thanks for your help.

Would SDL_GetKeyState() be the more efficient way due to the pointer?

The difference in efficiency is mostly that you don't have to update the array. SDL will update the array that is returned by SDL_GetKeyState even if you don't use it because SDL use it to keep track of which keys are down to be able to trigger key events correctly.
Topic archived. No new replies allowed.