James Kanze
10/1/2008 8:42:00 AM
On Sep 30, 4:27 pm, Pete Becker <p...@versatilecoding.com> wrote:
> On 2008-09-30 09:02:29 -0400, Zeppe
> <ze...@remove.all.this.long.comment.yahoo.it> said:
> > Pete Becker wrote:
> >> In this example, that's true. But there's nothing special
> >> about main.
> > There is, indeed.
> Well, yes, main is in some ways special. But we were talking
> about initialization, and the rule, once again, is that static
> objects must be initialized before the first entry into any
> function defined in the same translation unit. It doesn't
> matter whether the name of that function is main, foo, bar, or
> billy. And it doesn't matter whether main is also in that
> translation unit.
What the current standard says is that "if the initialization is
deferred to some point in time after the first statement of
main, it shall occur before the first use of any function or
object defined in the same translation unit as the object to be
initialized."
The standard doesn't really define what it means by use, which
makes it rather hard to figure out what is really meant. (Is
taking the address of an object "use"? What if the address is
used to initialize a static pointer?) On the whole, it opens
the door to possible cycles, in which the compiler is required
to initialized A before B, and B before A.
The issue is further muddled by the statement in the current
draft that "Non-local objects with static storage duration are
initialized as a consequence of program initiation." Again,
it's not really too clear what this means, but "program
initiation" certainly suggests "before the first statement in
main".
And of course, no compiler actually does defer the
initialization until after main. In practice, several
widespread idioms count on it, and no compiler would dare to
break them. So in practice, it's safe to say that
initialization does occur before the first statement in main,
even if the standard explicitly gives an implementation other
alternatives.
[...]
> > In addition, I'd say all the static variables from all the translation
> > units are initialised before main() is called.
> That's not required by the standard. The rule is as I've set out above.
> That's a provision for dynamically linked libraries, which can be
> loaded on demand, and don't initialize their statics until they are
> loaded.
And which also violate the phases of translation, and so are
"undefined behavior" as far as the standard is concerned.
(Obviously, implementations do define this behavior. Just as
obviously, if you're using dynamic linking, you turn to the
guarantees given by your implementation.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34