Expert C Programming

(Jeff_L) #1

When I wrote to Professor Knuth asking his permission to tell the story, and including a draft copy of
the chapter, he not only agreed, he marked numerous proofreading improvements on the text, and
pointed out that programmers can't distinguish NOV 27 from the other two dates, either.


This chapter presents a selection of C idioms that similarly depend on inside knowledge of
programming. Some of the examples here are useful tips to try, while others are cau-tionary tales of
trouble spots to avoid. We start off with a delightful way to make icons self-documenting.


Making a Glyph from Bit Patterns


An icon, or a glyph, is a small graphic for a bit-mapped screen. A single bit represents each pixel in
the image. If the bit is set, then the pixel is "on"; if the bit is clear, then the pixel is "off". So a series of
integer values encodes the image. Tools like Iconedit are used to draw the picture, and they output an
ASCII file of integers that can be included in a windowing program. One problem has been that the
icon appears in a program as just a bunch of hex numbers. A typical 16-by-16 black and white glyph
might look like this in C:


static unsigned short stopwatch[] = {


0x07C6,


0x1FF7,


0x383B,


0x600C,


0x600C,


0xC006,


0xC006,


0xDF06,


0xC106,


0xC106,


0x610C,


0x610C,


0x3838,


0x1FF0,


0x07C0,


0x0000


};


As you can see, the C literals don't provide any clue about how the image actually looks. Here is a
breathtakingly elegant set of #defines that allow the programmer to build the literals so that they look
like the glyph on the screen.


#define X )*2+1


#define _ )*2


#define s ((((((((((((((((0 /* For building glyphs 16 bits


wide */


They enable you to create the hex patterns for icons, glyphs, etc., by drawing a picture of the image
you want! What could be better for making a program self-documenting? Using these defines, the
example is transformed into:

Free download pdf