Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/5/84; site nsc-pdc.UUCP Path: utzoo!linus!philabs!cmcl2!seismo!harvard!talcott!panda!genrad!decvax!tektronix!reed!nsc-pdc!joemu From: joemu@nsc-pdc.UUCP (Joe Mueller) Newsgroups: net.lang.c Subject: Re: Re: C programming hint Message-ID: <463@nsc-pdc.UUCP> Date: Fri, 19-Jul-85 12:39:19 EDT Article-I.D.: nsc-pdc.463 Posted: Fri Jul 19 12:39:19 1985 Date-Received: Wed, 24-Jul-85 20:02:36 EDT References: <899@teddy.UUCP> <729@asgb.UUCP> <730@asgb.UUCP> Organization: NSC Portland Development Center, Portland Oregon Lines: 51 > > I found a way to initialize an array of characters without using a loop. > > Here is the method I used: > > > > char blanks[SIZE]; /* declare array of SIZE elements */ > > > > blanks[0] = ' '; /* initialize 1st element */ > > > > strncpy(blanks + 1, blanks, SIZE - 1); /* initialize entire array */ > > ^^^ ^^^ ^^^ > > | | | > > destination source how many characters to copy > > > > The trick is to use strncpy in an almost recursive way. > > Well, I hope you found this useful. > > Unfortunately, strncpy uses the "loop" that you are trying to avoid. It > also makes a redundant (in this case) check for the null character each time > through the loop that should be avoided. > > I would hope that the compiler (or optimizer) would realize what's > going on here, and do something a little more clever than looping. > especially since this is a strncpy, so the check for the null character > isn't done. I must admit that I am new to Unix C, but on VMS (and I > beleive TOPS20, for whoever uses that) C, the compiler will turn this > in to a MOVC instruction (or a BLT on the '20). These are both the accepted > method for filling a region. The most effecient way to initialize an array (or anything else) to anything but zeros is to use the initializer construct. If you need it to be zeros, any global will default to zero fill. This will only work for globals in most current compilers but the new ansi standard will (I believe) allow initialization of automatic aggregates as long as the initializer consists of constant expressions and doesn't make any subroutine calls or use variables. The following lines would initialize your blanks array as long as it has global scope (not in a function): char blanks[SIZE] = { ' ', ' ', ' ', ' ', ' ' }; /* 5 blanks */ char blanks[SIZE] = " "; /* 5 blanks */ This assumes a SIZE of 5, but you can do it for any SIZE; You can even skip your array dimention like this: char blanks[] = " "; /* 5 blanks */ If you want to know what I meant by the comments about the standard, let me illustrate: foo() { int bar[3] = { 3, 4, 5}; /* legal */ int baz[3] = { random(), open("foobar", O_RDONLY), bar[1]}; /* illegal */ }