hardcoded constants

T. William Wells bill at twwells.uucp
Sun Dec 18 18:49:05 AEST 1988


In article <1988Dec13.172306.16195 at utzoo.uucp> henry at utzoo.uucp (Henry Spencer) writes:
: In article <9134 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
: >>How much hard-coding is too much?
: >
: >Almost any is too much.  It is proper to use explicit constants when it
: >is clear what they mean and that they can never need to be changed.  For
: >example, assigning 0 or 1 to initialize a counter is proper.  Assuming
: >that 03 is always the right character code for a keyboard interrupt
: >character (i.e. ASCII ctrl-C) is not proper.
:
: The policy we try to follow is that if you must hard-code a constant,
: then it must be accompanied by a comment explaining why that particular
: number is there.

My rule is this: any constant which is used, explicitly or implicitly,
more than once gets a define. Any tunable parameter gets a define.
Anything else stays a constant.

The first covers using a constant explicitly, as in defining a[256],
and implicitly as in a[255], when the 255 is there because 255 ==
sizeof(a) - 1. These should be something like a[SIZEA] and a[SIZEA-1],
respectively.  However, it does not cover most uses of zero; zero
usually refers to either the first element of an array, a thing to be
converted to a null pointer, or a null character; all of which are
defined as part of the language and so don't require any definition
from me!

Some examples:

	cnt = 0;
	while (n) {
		cnt += n & 1;
		n >>= 1;
	}

does not get any defines; the 1's are part of the problem definition.
On the other hand,

#define DREG_RDY 0x01

	volatile char *dreg;

	while (*dreg & DREG_RDY)
		;

gets a define, the bit is defined in more than one place: the
hardware and the program.

---
Bill
{uunet|novavax}!proxftl!twwells!bill



More information about the Comp.lang.c mailing list