Clever Programming Tricks

Here is a collection of `programming tricks' which I have found useful. They come from various sources (which I will try to credit) and sometimes I have just invented them (probably for the umpteenth time). I am happy to add your favourite trick to the list -- just e-mail it to me.

Alan Mycroft


All of these tricks are intended to save a factor of at least two (and often ten or more) by local changes to code. Of course algorithmic improvement can provide much greater efficiency gains, so I am assuming that you have done all you can in this respect, BEFORE using these tricks.

Algorithmic Ideas

Low level hacks

These are all coded in strictly conformant ANSI C; we use 'unsigned' arithmetic to ensure overflow is ignored. Numeric postfixes like `unsigned32' mean that *at least* 32 bits are required to make this work. (ANSI C guarantees `long' has at least 32 bits, but does not necessarily provide a type suitable for `int64' etc). General assumption. If a routine tests (e.g.) a 32-bit integer having a certain property then the actual argument is assumed to be zero-extended to the size of the container type. References: (Search for hakmem on the web) e.g. section of