Initializing Static Variables

Steve Summit scs at adam.mit.edu
Tue Feb 26 12:48:01 AEST 1991


In article <13704 at hacgate.UUCP> wdelv at devnet3.UUCP (walt del vecchio) writes:
>I've tried searching for the answer in "The C Programming Language" by K & R
>as well as in the regularly posted FAQ's without success.
>Does the declaration of a static int, for example, establish a variable
>with an initial value of zero ?

Inconceivable!  (Sorry; I just read The Princess Bride again.)
*Three* FAQ list sneak-previews in one month!

89.  What can I safely assume about the initial values of variables
     which are not explicitly initialized?  If global variables start
     out as "zero," is that good enough for null pointers and floating-
     point zeroes?

A:   Variables with "static" duration (that is, those declared outside
     of functions, and those declared with the storage class static),
     are guaranteed initialized to zero, as if the programmer had typed
     "= 0".  Therefore, such variables are initialized to the null
     pointer if they are pointers, and to 0.0 if they are floating-
     point.  This requirement means that compilers and linkers on
     machines which use nonzero internal representations for null
     pointers and/or floating-point zeroes cannot necessarily make use
     of uninitialized, 0-filled memory, but must emit explicit
     initializers for these values (rather as if the programmer had).

     Variables with "automatic" duration (i.e. local variables without
     the static storage class) start out containing garbage, unless they
     are explicitly initialized.  Nothing useful can be predicted about
     the garbage.

     Dynamically-allocated memory obtained with malloc and realloc is
     also likely to contain garbage, and must be initialized by the
     calling program, as appropriate.  Memory obtained with calloc
     contains all-bits-0, but this is not necessarily useful for pointer
     or floating-point values.

                                            Steve Summit
                                            scs at adam.mit.edu



More information about the Comp.lang.c mailing list