static versus auto initialization

John Mundt john at chinet.chi.il.us
Fri Jan 20 05:40:40 AEST 1989


In article <8901182125.AA06523 at decwrl.dec.com> devine at cookie.dec.com (Bob Devine) writes:
>
>  Would someone explain to me why the discrepancy between the
>uninitialized elements of static and auto arrays?  Someone in
>our group asked me a question on this point and the best answer
>that I could generate was, in essence, "Cuz D.R. did it for speed".
>
>  The problem looks like this:
>
>        static char abc_static [5] = { 'a', 'b', 'c' };
>        main()
>        {
>            auto char abc_auto [5] = { 'a', 'b', 'c' };
>            . . .
>        }

When the compiler creates the executable program, there is a special
area created for static and global variables.  The address is fixed
at compile time and will only hold abc_static values.  The "static"
is not really necessary here.  "static" here does not make it static
since it is already static by virtue of being global.  Instead, the
"static" notation serves to make it global to the file it is in.  
Thus, if you had a program made up of main.c, part2.c, and part3.c,
and this were in main.c, only functions in main.c could address and
use abc_static.

When abc_auto is created, it is created on the fly and on the stack
when main() is run.  It's address is computed as the address of the
base off the stack plus an offset to each member of abc_auto.
Since the stack is constantly reused and not initialized, the value 
of abc_auto[4] is whatever happened to be in that memory location.  
A static variable will run faster if it is addressed scads of times
since its final address does not have to be computed each time it
is accessed.  



-- 
---------------------
John Mundt   Teachers' Aide, Inc.  P.O. Box 1666  Highland Park, IL
john at chinet.chi.il.us
(312) 998-5007 (Day voice) || -432-8860 (Answer Mach) && -432-5386 Modem  



More information about the Comp.lang.c mailing list