Sunday, September 25, 2011

Issue With gameIO::keyboardPressed Function

A student discovered that he was unable to get the arrow keys working using the skeleton io_demo code provided for Assignment 1, despite the fact that other keys seemed to work fine.

As it turns out, the main issue is with the data type chosen for the argument key: char.  This is a signed data type, but the DIK_* values used to identify the keys chosen are in the range of 0-255.  So when an arrow key value like DIK_RIGHTARROW - which is over 200 - is interpreted as a signed value, it ends up being negative (due to the most significant bit being 1).  This means that when we index mKeyboardState we are actually referencing memory that is before the start of the array.  If that memory happens to contain just the right thing (which is easy to do - all it needs is to have its most significant bit being 1), our function will return true even if the right arrow is not being pressed.

The solution is simple: just change the argument type to be an unsigned char or cast the argument to be unsigned before using it to index the array.

No comments:

Post a Comment