# Cute Tricks in C

This is a collection of short cute tricks that can be done in C (and probably in most other languages) to make the code smaller, cleaner, or faster.

## Powers of Two

    int PowerOfTwo (unsigned i)
    {
        /*
         * Returns TRUE if "i" is a power of 2 (has only one bit on).
         * Doesn't work for i == 0 (returns TRUE).
         */

        return ((i - 1) & i) == 0;
    }

## Unrolling Small Loops

        switch (length) {
    	case 16:	*to++ = *from++;
    	case 15:	*to++ = *from++;
    	case 14:	*to++ = *from++;
    	case 13:	*to++ = *from++;
    	case 12:	*to++ = *from++;
    	case 11:	*to++ = *from++;
    	case 10:	*to++ = *from++;
    	case 9:		*to++ = *from++;
    	case 8:		*to++ = *from++;
    	case 7:		*to++ = *from++;
    	case 6:		*to++ = *from++;
    	case 5:		*to++ = *from++;
    	case 4:		*to++ = *from++;
    	case 3:		*to++ = *from++;
    	case 2:		*to++ = *from++;
    	case 1:		*to++ = *from++;
    	default:;
        }

If there's a chance that length will be greater than 16, then put the default case at the top and loop until length <= 16. Add a no-op "case 0" at the end.

## Unrolling Bigger Loops

This is called Duff's Device, after Tom Duff. Note that it doesn't work when length == 0.

        loopcount = (length + 15) / 16;
        switch (length % 16) {
    	case 0: do {	*to++ = *from++;
    	case 15:	*to++ = *from++;
    	case 14:	*to++ = *from++;
    	case 13:	*to++ = *from++;
    	case 12:	*to++ = *from++;
    	case 11:	*to++ = *from++;
    	case 10:	*to++ = *from++;
    	case 9:		*to++ = *from++;
    	case 8:		*to++ = *from++;
    	case 7:		*to++ = *from++;
    	case 6:		*to++ = *from++;
    	case 5:		*to++ = *from++;
    	case 4:		*to++ = *from++;
    	case 3:		*to++ = *from++;
    	case 2:		*to++ = *from++;
    	case 1:		*to++ = *from++;
    		} while (--loopcount);
        }

## Counting Bits

This routine counts the number of set bits in time proportional to the number of set bits:

        count = 0;
        while (testnum) {
    	testnum &= testnum - 1;
    	count++;
        }