Pieces of working but unusual code

This page contains examples of unusual code that is worth to have a look at.

What you will see here:

  1. A riddle
  2. The C ?: operator


A riddle

The code cited below is from an usenet article posted in 1993 in comp.lang.c. The original author is Doug Merrit (doug@netcom.com). I've reformatted the header lines but otherwise not touched the article.

From moppi!sunflower.sub.org!transtec.de!xlink.net!howland.reston.ans.net!
vixen.cso.uiuc.edu!sdd.hp.com!decwrl!decwrl!csus.edu!netcom.com!doug
Thu Aug 05 21:30:09 MSZ 1993
Newsgroups: comp.lang.c
Path: moppi!sunflower.sub.org!transtec.de!xlink.net!howland.reston.ans.net!
vixen.cso.uiuc.edu!sdd.hp.com!decwrl!decwrl!csus.edu!netcom.com!doug
From: doug@netcom.com (Doug Merritt)
Subject: puzzle: code found in Huge Program From Hell
Message-ID: <dougCB6z7J.DvI@netcom.com>
Organization: Netcom Online Communications Services (408-241-9760 login: guest)
References: <23hi4m$tb@news.cs.tu-berlin.de> <64823@aurs01.UUCP>
<dougCB6xJo.B0v@netcom.com>
Date: Tue, 3 Aug 1993 16:30:55 GMT
Lines: 31

Here's a fun puzzle for y'all. I was reading through 2000 lines of
uncommented dense code that's part of an even larger complex and ancient
body of code (the proverbial Huge Program From Hell :-) and found
the following gem...after puzzling over it for a bit I realized that
it was a rather clever algorithm, one that I'll doubtless find use
for in the future:

function(value)
        unsigned int    value;
{
        int count;

        for (count=0; value; count++)
                value &= (value - 1);
        return(count);
}

This was actually embedded in a huge function, but never mind that. 10
points to anyone who already knows this algorithm. Also 10 points to anyone
who figures out what it does within 2 minutes. Bonus points if you
can prove that it is correct (modulo any typos I may have introduced :-)
Yet extra bonus points for comparing it to the other three well known
algorithms for doing the same thing.

30 points to anyone who can apply the general idea to solve a completely
different problem (it is suggestive but I haven't found another application
yet, myself).
        Doug
--
Doug Merritt                            doug@netcom.com
Professional Wild-eyed Visionary        Member, Crusaders for a Better Tomorrow


The C ?: operator

The ?: operator is very useful in writing cryptic code in C. If you combine this operator with a missing knowledge of the representation of boolean values in C, you will get interesting results.

The stuff below is from a big (and buggy) library that is in use somewhere (no details, sorry:-).

  if (LotIndex < usNumLots?(LotIndex >= 0?1:0):0) {
    memcpy(pUnitId, pCurrentRun->lot[LotIndex].track_num, LEN_TOOL_TRACK);
  }

Three big cheers for you if you can decide in less that 10 seconds under which conditions the code inside the if clause is executed.

Go back.


snworking.html; last change: 01-Aug-98
uz@musoftware.de