A89: Re: Re: Just subscribed... my first question


[Prev][Next][Index][Thread]

A89: Re: Re: Just subscribed... my first question




Hi!

> Your explanation seems to make sense, but I have an example from my code
> that contradicts it.

He, he, he... In fact, everything depends of the concrete example. I will
explain this through the text... In a general, "static" can make program
shorter if it is initialized with a lot of non-zero data...

> In  main():
> 
> term *groups[MAX_VARS] = {NULL};
> 
> term is a typedef for a struct that contains two unsigned ints and a
> pointer. MAX_VARS is 16. The program with the above line compiles to 2421
> bytes and requires bzero(), which I assume is similar to the bcopy
routine
> you mentioned.

The difference between bcopy and bzero is huge: bcopy copies a sequence of
bytes from one place to another (similar like memcpy, but the size is a
word instead of longword). But, bzero fills a memory zone with zeros. It
does not copy them from anywhere...

> When I change it to this:
> 
> static term *groups[MAX_VARS] = {NULL};
> 
> it compiles to 2427 bytes and doesn't require anything from inits.o. So
even
> without the extra overhead of the inits.o it is still 6 bytes bigger when
I
> use static.

Your array is initialized to a lot of NULLs (which are in fact zeros:
4-byte
long zeros). So, the compiler must put 16 zeros in the code, and make
"groups"
point to them. 16x4 bytes = 64 bytes... But when you don't use "static",
the
initializer data need not to be stored in the code, because the data is
"all-zero", so the compiler will use just "bzero" to fill it with zeros...

> Just for fun, I changed the MAX_VARS to 1600. Now the size difference is
> huge. With static: 8783. Without: 2463. My first guess is that the use of
> static in this case causes the whole array to be stored in the file, but
the
> math doesn't seem to come out right.

Your guess is good. And, 1600*4=6400. So, your static array takes 6400 of
spare bytes in the file. And, 8783-2463=6320, which is nearly the same.
The difference between 6400 and 6320 is due to different handling of
static and auto variables.

The conclusion: "static" arrays are very good for something like:

static int a[20]={5,8,2,3,7,6,4,2,3,1,9,8,7,5,2,3,10,6,0,4};

and very bad for something like:

static int a[5000]={};

By the way, if you need to have a global array, (e.g. array declared
out of any function), it always will be treated as static from the 
aspect of storage (this is a known fact in C), although it is not
explicitely declared as "static" (in such case, word "static" means
"local for this module" - you mentioned this in your first letter). 
Then, instead of

int a[5000]={};

which will produce overhead of 10000 bytes in the file, it is better to
use:

int *a=NULL;

then allocate it in the run-time with

a=calloc(5000,sizeof(int));

> So bottom line: I'm confused. And tired. Goodnight.

I hope that you are now not confused. And, not tired ;-)

Zeljko