array init'ing, static or auto?

Doug Gwyn gwyn at smoke.BRL.MIL
Tue Nov 14 07:58:44 AEST 1989


In article <2679 at dogie.macc.wisc.edu> yahnke at vms.macc.wisc.edu (Ross Yahnke, MACC) writes:
>  wubba()
>  { char wubbaStr[] = "wubba";
>when does actually get init'ed? When the function is called?

This is an attempted initialization of an auto aggregate,
which is not supported by many C implementations.

>If wubba() got called a few thousand times, would it be faster
>to make wubbaStr static instead?
>  wubba()
>  { static char wubbaStr[] = "wubba";
>I'm assuming it would be cuz wubbaStr would get init'ed at program
>load time, and not when the function is called... any comments?

To avoid implementation dependencies, let's recast the question
in terms of portable C:

wubba(){ int wubbaInt = 42;
	vs.
wubba(){ static int wubbaInt = 42;

The "static" case initializes the variable just once,
before the program starts to execute (perhaps at link time).
The "auto" case (i.e. the non-"static" one) initializes
the variable each time the block (function body) is entered.

There are advantages and drawbacks to both methods.
Static initialization is probably less computationally expensive,
but if you change the variable the change will "stick", so that
the next time the block is entered the NEW value will be in effect.
Sometimes that is exactly what you want, but more often it isn't.



More information about the Comp.lang.c mailing list