avoiding explicit array sizes (was: Point me in the right direction)

Peter Swain swine at ccicpg.UUCP
Sat Feb 18 19:28:01 AEST 1989


In article <807 at atanasoff.cs.iastate.edu> hascall at atanasoff.cs.iastate.edu (John Hascall) writes:
	[ .. week-long discussion deleted .. ]
>>double fund_consts[] = {
>>	3.14159265,
>>	2.7182818,
>>	6.02E23,
>>};
>
>   Of course, adding:
>     #define N_FCONSTS (sizeof(fund_consts)/sizeof(double)) 
>   then you can use stuff like:
>     extern fund_consts[N_FCONSTS];
>   elsewhere.

In recent years, i've often gone in precisely the other direction.
One of the hassles of large systems is the proliferation of names,
all looking very much alike.
You've just added another name (N_FCONSTS) for the programmer
to remember.

Admittedly the concept it embodied was tedious to type,
but it was quite derivable!

Try using 
	#define dim(a)	(sizeof(a)/sizeof(*(a)))
and you can elegantly express the size of any array.

it leads to such things as:
	for (i = 0; i < dim(fund_consts); i++)
		magic(i);
or
	p = buf;
	 ....
	while (p < &buf[dim(buf)])
		stuff(*p++);

where there is no question that the appropriate bound has been used.

Don't you always leave out a few letters when thinking up a name
to #define for a manifest constant? They all end up as N_THNGS & etc,
and tend to converge in a large project.

If the size of an array is a core concept, then it *should* have a name,
but if it's just a collection of like things, I like to keep the dimension
quite anonymous.

This can go to extremes, and sometimes I've been known to say:
	int things[200];		/* big enuff */
	int thungs[dim(things)+1];	/* one for each thing, plus sentinel */
all in order to avoid thinking of a new name.


all we need now is a typeof(lvalue) operator to complement sizeof(),
and i'd be happy!
-- 
Peter Swain                                       Softway Pty Ltd
swine at softway.oz.au                               PO Box 305
uunet!ccicpg!swine                                Strawberry Hills, NSW
                                                  Australia



More information about the Comp.lang.c mailing list