Finding Available Length Of Strings...

Mark Brader msb at sq.sq.com
Sat Nov 17 18:02:28 AEST 1990


> EASY SOLUTION:
> If all the strings you will be using are less than some number N (and
> you have enough memory), then create a constant:
>     #define MAX_LEN        N
> ... Now define all your character arrays as:
>     char name[MAX_LEN];
> when performing loops, range checking, etc., use MAX_LEN 

It generally seems to me to produce clearer code if the constant that
one defines specifies, not the length of the buffer (as above), but
the maximum length of the string contained in it.  That is:

	char name[MAX_LEN+1];		/* +1 for '\0' */

If you use this declaration style routinely, you get rid of a lot
of -1's scattered through the code wherever there are loops and limit
checks; and if you do make an off-by-one error, it tends to fail safe.

It is conceded that the preference for this is somewhat a matter of
opinion, and followups merely to agree or disagree with this opinion
are dissuaded.  Likewise for the presence or absence of the comment.
-- 
Mark Brader			"It's simply a matter of style, and while there
SoftQuad Inc., Toronto		 are many wrong styles, there really isn't any
utzoo!sq!msb, msb at sq.com	 one right style."	-- Ray Butterworth

This article is in the public domain.



More information about the Comp.lang.c mailing list