Expressions in initializers
Chris Torek
torek at elf.ee.lbl.gov
Mon Mar 4 20:59:22 AEST 1991
In article <760 at ajpo.sei.cmu.edu> rabbieh at 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 at ee.lbl.gov
More information about the Comp.lang.c
mailing list