Initializing arrays of char

Mark Brader msb at sq.sq.com
Thu Oct 18 15:46:38 AEST 1990


> Anyone who wants character arrays initialized with "regular"
> strings should always be using
> 	char a[] = "hello";
>
> Both	char a[6] = "hello";
> and	char a[5] = "hello";
> are risky, and both "open the door for a ton of mistakes to get
> through."  Neither should be used in the normal case, but in the
> abnormal case, when you've taken character counting upon yourself
> for whatever reason and are prepared to live with the
> consequences, either seems appropriate  ...

Agreed.  A particularly tricky case, though, is this one:

	#include "foo.h"

	char bar[BAR_LEN] = "initial bar";

which gives surprising results if you think that strlen("initial bar")
is safely less than BAR_LEN, and it really is equal to it.  However,
this is a fairly rare form of initialization, and I wouldn't give
much weight to the point I just raised.  X3J11 chose rightly, I think.
-- 
Mark Brader		   "I don't care HOW you format   char c; while ((c =
SoftQuad Inc., Toronto	    getchar()) != EOF) putchar(c);   ... this code is a
utzoo!sq!msb, msb at sq.com    bug waiting to happen from the outset." --Doug Gwyn

This article is in the public domain.



More information about the Comp.lang.c mailing list