Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ames!elroy!peregrine!ccicpg!swine From: swine@ccicpg.UUCP (Peter Swain) Newsgroups: comp.lang.c Subject: avoiding explicit array sizes (was: Point me in the right direction) Summary: finding dimension of array Message-ID: <14647@ccicpg.UUCP> Date: 18 Feb 89 09:28:01 GMT References: <23631@watmath.waterloo.edu> <1841@mit-caf.MIT.EDU> <807@atanasoff.cs.iastate.edu> Reply-To: swine@ccicpg.UUCP (Peter Swain) Organization: Computer Consoles Inc. (CPD), Irvine, CA. Lines: 59 In article <807@atanasoff.cs.iastate.edu> hascall@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@softway.oz.au PO Box 305 uunet!ccicpg!swine Strawberry Hills, NSW Australia