Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!tut.cis.ohio-state.edu!ucbvax!dog.ee.lbl.gov!elf.ee.lbl.gov!torek From: torek@elf.ee.lbl.gov (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Expressions in initializers Keywords: initializers Message-ID: <10554@dog.ee.lbl.gov> Date: 4 Mar 91 10:59:22 GMT References: <760@ajpo.sei.cmu.edu> Reply-To: torek@elf.ee.lbl.gov (Chris Torek) Organization: Lawrence Berkeley Laboratory, Berkeley Lines: 62 X-Local-Date: Mon, 4 Mar 91 02:59:22 PST In article <760@ajpo.sei.cmu.edu> rabbieh@ajpo.sei.cmu.edu (Harold Rabbie) writes: >Here's one for the comp.lang.c.lawyers - K&R 2 says (without explanation) >that non-constant expressions can be used as initializers only for static >scalars, not for automatics, and not for aggregates. I think you have misread something here. Initializers must be constants *except* when: a) the variable being set is automatic, and b) the variable being set is not an aggregate. >e.g. >static double x = sqrt( 2.0 ); Illegal; x is not automatic. >void foo( void ) { double x = sqrt( 2.0 ); } Legal: x is automatic and not an aggregate (not a structure, union, nor array). >static struct foo { > double x; >} bar = { sqrt( 2.0 ) }; Illegal; bar is not automatic. The more interesting case is: void silly(void) { struct silly { double x; } bar = { sqrt(2.0) }; } which is illegal, even though `bar' is automatic and `bar.x = sqrt(2.0);' is legal. >What's the deal here - is ANSI easing up on those no-good implementers :-) >or is there a valid reason for this restriction? Apparently the theory behind this particular example is that constant aggregate initializers can be compiled into calls to memcpy(): void silly(void) { struct silly { double x; } bar = { 3.142857142857143 }; } is in some sense equivalent to: void silly(void) { static struct silly { double x; } __L1 = { 3.142857142857143 }; struct silly bar; memcpy((void *)&bar, (void *)&__L1, sizeof bar); } and this is somehow considered to have some advantage over: void silly(void) { struct silly { double x; } bar; bar.x = 3.142857142857143; } -- In-Real-Life: Chris Torek, Lawrence Berkeley Lab EE div (+1 415 486 5427) Berkeley, CA Domain: torek@ee.lbl.gov