"static" means too many things

bearophile bearophileHUGS at lycos.com
Tue May 1 16:46:37 PDT 2012


This is the brief of some D code, it shows one consequence of the
excessive overloading of the D "static" keyword:

struct Foo {
     bool solve() {
       /*static*/ bool fill(int r, int c, Cell n) {
           // ...
           if (fill(r + i, c + j, n + 1))
             return true;
       }

       return fill(x, y, 1);
     }
}

The Foo struct has solve() instance method, solve() contains and
calls a nested (recursive) function named fill().

fill() has to use instance attributes, so it can't be a static
struct function regarding the struct Foo. On the other hand the
nested function fill() doesn't need variables defined inside the
method solve(), so it doesn't require a frame pointer to solve(),
so it's static for solve().

The problem is that "static" is used to denote both nested
functions that have no frame pointer (they are often faster and
they tend to be less buggy because they can't use names from
outer scopes, almost like pure functions), and static struct
methods :-)

So to denote a function that doesn't need a frame pointer
something like "@noframe" sounds better than "static".

In practice this is not a very common situation, and fill() here
is not performance-critical, so keeping the frame pointer is not
so bad (I also annotate fill() with "pure", so despite not being
static to solve() it's able to use only immutable names from the
scope of solve()).

Where performance is very important it suffices to pull fill()
out of solve(), define it as a private instance method, and maybe
rename it to _fill() or something similar.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list