CPB Mailing List

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

Re: static functions



On Fri, 6 Mar 1998, Hibbs, Philip wrote:

> General C++ question: What is the effect of declaring a function as
> static?
> 


Yes, this is a general C++ question, although it is often misunderstood,
because of the contexts it can be used in.

// file test.cpp (didn't compile it, so excuse typos)

// First the typical C uses of static...

int foo; // global variable, visible to all modules at link time
static int foofoo; // global variable, but only visible to the module
                   // in which it was declared.

static int function(); // function visible only to the file it is in

int anotherFunction()
{
  static int beenHere; // declared in same memory segment as "foofoo"
                       // but is only available to this function.  It
                       // is not on the stack, and retains its value
                       // between invocations of this function.  Also, it
                       // is not initialized until the first call to
                       // this function.
}

// Now some added C++ uses of static

class Foo
{
public:
  static int Method(); // You don't need a Foo instance to call this
                       // method, it is scoped in the Foo class.  To
                       // call it, use Foo::Method()
  static int Count;    // Just like a global variable, only it must be
                       // accessed with Foo::Count
};

int Foo::Count;  // All static class variables must be defined

inline inlineFunction()
{
  static int someInt;
  doSomething();
}

The above, inlineFunction is *very* dangerous.  The reason is that you
will get one instance of someInt for each invocation of the function.
It's static, that's true, but the compiler expands this function every
time you call it.  Some compilers will not allow inline functions with
static data, but don't count on it...


Off the top of my head, that's all I can think of.  I'm sure someone will
let us know if I've forgotten a use or two.

	-jody


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