When should variables within blocks be allocated?

Henry Spencer henry at utzoo.uucp
Sat Jan 20 05:16:55 AEST 1990


In article <26449 at stealth.acf.nyu.edu> brnstnd at stealth.acf.nyu.edu (Dan Bernstein) writes:
>If a function contains the statement if(0) { int k[100000000]; ... },
>should the space for k be allocated? Every compiler I've tried allocates
>variables at function entry like Tom's, but it would be nice to save
>100M of memory if k is never used. I can't find any ANSI rules on this.

It's covered by the as-if rule:  if it's never used, you can't tell whether
it was allocated or not, so the compiler is entitled to optimize it out.
See 2.1.2.3 for the formal statement of the as-if rule.

>If the answer is that the space for k can be ignored, are there any
>compilers smart enough to optimize k away? Are there any compilers that
>go all the way and allocate k the moment they enter the block? Is the
>space saved worth the efficiency loss?

Compilers that do smart register allocation have at least a fighting chance
of noticing that k is never used, although it being an array might complicate
things.  Most current compilers do all their allocation at function-entry
time:  it's usually more efficient and it simplifies stack-frame management.
-- 
1972: Saturn V #15 flight-ready|     Henry Spencer at U of Toronto Zoology
1990: birds nesting in engines | uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.lang.c mailing list