structure inits

g-frank at gumby.UUCP g-frank at gumby.UUCP
Wed Jan 23 23:41:53 AEST 1985


> Q: Why is it ok to init a structure in line #7
>    but not local like in line #12 ?
> 
> ---------------------------------------------------------------------
> 1    struct a {
> 2         int size;
> 3         char stuff[25];
> 4         short flag;
> 5    };
> 6    
> 7    struct a item = { 256000, "Whatever", 1 };
> 8    
> 9    any()
> 10   {
> 11        struct a item2 = item;                 /* no problem..... */
> 12        struct a bomb = { 128, "str", 1 };     /* no go for local */
> 13   }
> ----------------------------------------------------------------------
> 

  The structure in line 7 is (obviously) a static; that is, it lives in the
program's data segment and therefore constitutes "initialized storage."
To put it a bit more clearly, at execution time the initialized portion of
the data segment (which generally includes string constants and such) is
loaded directly from a portion of the binary.

   The structure in line 12, being an auto, i.e., allocated on the stack
on every entry to the function any(), doesn't have the same initialization
mechanism.  Code would have to be generated reload its value at every entry to
the function.  Therefore, to stress this point (?), such initializations are not
permitted for autos, even though explicit assignments (line 11) are.

   If you want to do something like line 12, you can declare bomb to be
static; then the syntax is acceptable.  Remember though, that if you 
change the value of bomb, it will stay changed, just as item will.

   By the way, I don't think there really is a defensible reason for this
non-orthogonality.  I don't need any points stressed by language designers,
particularly in C.  If one is going to initialize a structure anyway, the
language may as well permit it to be done in a consistent manner.


-- 
      Dan Frank

	"good news is just life's way of keeping you off balance."



More information about the Comp.lang.c mailing list