galaxy%UCB-VAX@ucscc.UUCP (01/22/85)
Been wanting to know about local, global struct initialization. I haven't seen this Q addressed; also, this may be an item for all this discussion about standardization. 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 } ---------------------------------------------------------------------- ...using cc(1) on a Vax 780, running 4.2 BSD Thanks. Replies: ucscc!galaxy@BERKELEY galaxy%c%ucsc@csnet-relay
g-frank@gumby.UUCP (01/23/85)
> 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."