Justin Robbs wrote:
>
> I need to fill a number of character fields with spaces or zero's
> depending on the field. Which method is faster.
Answer #1: It's impossible to say. The C language
is implemented on many platforms with different performance
characteristics. Method X may be faster than Method Y on
Platform A, but slower on Platform B, and run at identical
speed on Platform C.
Answer #2: It is surpassingly unlikely that the speed
of such a trivial operation will have any detectable effect
on the speed of your program. You are almost certainly
optimizing the wrong thing; an old friend of mine used to
characterize this as "Cleaning the bottle caps off the
beach so the sand will be nice and smooth around the
whale carcasses."
Answer #3: Interspersed below.
> char var[10] = " ";
> var[9] = '\0';
First, this isn't "filling a field," it's initializing
an array and then overwriting part of it. The distinction
is important because the first line works only as an
initializer; you can't just assign arrays with the `='
operator.
Second, it's silly. You initialize `var' to contain
nine spaces followed by a zero, and then you overwrite that
zero with another zero. What's the point of the overwrite?
> or
>
> char var[10];
> sprintf( var, " " );
This is probably the slowest of the alternatives you've
presented. No guarantees, of course.
> or
>
> char var[10];
> strcpy( var, " " );
> var[9] = '\0';
Again, why set var[9] to zero twice? Are you afraid it
won't remember its value unless reminded? ("Hey there,
var[9]: Pay attention or I'll make you stay after class and
clean the erasers!")
> int i;
> char var[10];
> for(i=0; i<10; i++)
> {
> var[i] = ' ';
> }
> var[i] = '\0';
Why set var[9] to a space, only to turn right around and
overwrite the space with a zero? You could save time (HUGE
amounts of time

by stopping the loop after nine iterations
instead of ten.
> Thanks for the help.
You're welcome. The biggest help I think I can be is to
suggest that you not worry about the speed of such a trivial
thing until and unless you've *measured* the performance of
your program and determined that the timing of this fragment
is crucial. (A consequence of this philosophy of "help" is
that I'm not even going to mention the manymanymany other
ways you might go about this task.)
--