CPB Mailing List

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: static functions




> Not true. Because it is static, by definition it will be initialized to 0
> (zero) before main() is called.

That's almost true.  Every variable which is *not* declared in a function
and thus on the call stack, will be initialized *by the compiler* in one of
the data segments of the resulting output file.  So you are right that it
will have a value of zero, but because it's set up by the compiler and
simply loaded when the program is loaded.  However, my point was that it
doesn't get constructed (or initialized) at run time until the first
invocation of the routine.  Perhaps I chose a poor example.  Hopefully this
will clear it up....

void foo()
{
  static Bar bar;  // Bar is some class
}

In this case, Bar will have memory set aside (and initialized to all
zeroes).  However, the constructor will not be called *until* the first
time through the foo function.  If foo is never called, the object is never
constructed.  Also note that in the following case,

void foo2()
{
  static int a = 1;
}

that a is initialized to zero (by the compiler), but is not mandated to be
set to 1 until foo2() runs.  Some compilers will automatically fix up some
data segments to do this, but it is not guaranteed to be so.  In *no case*
however, will an object have it's constructor called until the function is
called.

Hope this is clear.

	-jody



W Komornicki's Home Page | Main Index | Thread Index