Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Given an input device (basically a keyboard) that reports keyup and keydown, how may I most efficiently store and retrieve information about which keys are currently depressed? My first thought was a dynamic array, but maintaining and searching a dynamic array seems like a serious drain on resources.

Many thanks in advance for any help


share|improve this question
Why would that be a major drain on resources? –  John Feb 17 '13 at 14:56
You can use bit flags easily enough for this and it would be very fast to determine what buttons are depressed. –  Akira71 Feb 17 '13 at 14:57
sorry, bit flags? –  jamesson Feb 17 '13 at 14:59
john: well, an array of undefined length + searching it every time to see if a particular button is depressed seems like a good way to waste resources and slow down the program. Maybe I'm not understanding something correctly (always a possibility :)). –  jamesson Feb 17 '13 at 15:02
@jamesson Sorry, here is an interesting explanation for C++ but they exists for any major language. cplusplus.com/forum/general/1590 . I will try to write up a nice explanation as an answer if I can in a bit (or anyone else) but I think this is a great solution for you. I have used bit flags for enumerating input types on embedded devices a fair bit as they are fast and memory efficient. –  Akira71 Feb 17 '13 at 15:04

1 Answer 1

A fixed-length array will work just fine, since the number of keys can't change. So, make an array, call it depressed, of length N, where N is the number of keys on your input device. When key X is depressed, set depressed[X] to True. When key X is released, set depressed[X] to False. To report the True/False state of any given key, you'll need a mapping from user-/API-level names, to indices into your array. e.g. MOTOR_REVERSE_TOGGLE -> position 6 in your array.

As for efficiency, an array should be adequate for space, unless you've got very tight memory restrictions on whatever device you're programming. In that case, you'd use a bitfield to store the data. Basically, it's the same as your array, except instead of words being set to True or False (which would end up a some magic numbers, say for example 11111111 and 00000000), you set individual bits in a word to 1 or 0.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.