Afficher un message
Vieux 02/06/2008, 04h49   #5
copx
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: static and initialization rules or 0 is 0.0 is NULL


"Bartc" <bc@freeuk.com> schrieb im Newsbeitrag
news:6DH0k.1730$E41.1587@text.news.virginmedia.com ...
>
> "copx" <copx@gazeta.pl> wrote in message
> news:g1v9jg$p23$1@inews.gazeta.pl...
>>I don't know what to think of the following..
>> (from the dietlibc FAQ)
>> Q: I see lots of uninitialized variables, like "static int foo;". What
>> gives?
>> A: "static" global variables are initialized to 0. ANSI C guarantees
>> that.
>> Technically speaking, static variables go into the .bss ELF segment,
>> while "static int foo=0" goes into .data. Because .bss is zero
>> filled by the OS, it does not need to be in the actual binary. So it
>> is in fact better to not initialize static variables if the desired
>> initialization value is 0 anyway. The same is true for pointers, by
>> the way. On all platforms supported by the diet libc, numeric zero
>> is also the pointer value for NULL. So not initializing a static
>> pointer yields NULL.
>>
>> So far I am still initializing all my variables by hand. I could save a
>> lot of code if I removed all the to zero/NULL initializations for static
>> globals..

>
> You might save some typing. I doubt it will make the program smaller.


It does. Example:

static int foo;

void lib_init(void)
{
foo = 0;
}

Compile and check the assembly. The compiler has to put the code to set foo
to 0 into lib_init() because it cannot know when lib_init() might be called.
It is perfectly possible that lib_init() will be called after the value of
foo has been changed by some other function.
In theory a compiler could remove such code in some cases if it does whole
program optimization and hyper-advanced program flow analyses to figure out
that lib_init() will indeed only be called once and at a time when foo is
still guaranteed to be zero.
However, even if such a god-like compiler existed, the optimization routine
wouldn't work in cases where the program flow is not predictable at compile
time (it often isn't).


  Réponse avec citation
 
Page generated in 0,05442 seconds with 9 queries