logo       
Google Custom Search
    AddThis Social Bookmark Button

static variables with function scope: msg#00011

Subject: static variables with function scope
> The problem in Pike is that the intended lifetime of the variable
> isn't always obvious; consider nested classes:
> 
>   class X {
>     int inc()
>     {
>       static int counter;
>       return counter++;
>     }
>   }
> 
>   int main()
>   {
>     function(:int) X1 = X()->inc;
>     function(:int) X2 = X()->inc;
>     write("X1:%O,%O\n"
>         "X2:%O\n",
>         X1(), X1(),
>         X2());
>   }
> 
> Should the above output X1:0,1 X2:0, or X1:0,1 X2:2? ie should the
> variable be stored in X or in the top-level class?

My intuition says storage should be where it was declared, i e X1:0,1
X2:0 with the above example. Given the proposed semantics, for:

  class X {
    static int counter;
    int inc()
    {
      return counter++;
    }
  }

...I would consider X1:0,1 X2:2 be the correct corresponding output.
You don't state whether this case, where the "static" modifier already
has semantics tradition in Pike, will do the same thing, though. Would
and should it?

> Pike also has nested functions; consider:
> 
>   function(:int) X()
>   {
>     int inc()
>     {
>       static int counter;
>       return counter++;
>     };
>     return inc;
>   }
> 
>   int main()
>   {
>     function(:int) X1 = X();
>     function(:int) X2 = X();
>     write("X1:%O,%O\n"
>         "X2:%O\n",
>         X1(), X1(),
>         X2());
>   }
>
> Same question.

I'm less opinioned here; I would not mind X1:0,1 X2:2 in this case, or
the first option, as long as which result you'd get is guaranteed.

> I believe that the most useful would be to store the variable in the
> closest surrounding scope (ie X1:0,1 X2:0 for both of the above),
> and then have some extra syntax for specifying some other scope.

I think the most useful is the most readable (least susceptible to
misunderstanding, when the code is read by humans). Which one that is,
I don't know; I'm just one data point there. I can understand and to
some extent appreciate that the proposal above would be the easiest to
implement / maintain, if that is what you meant, but since you suggest
supporting both, it probably wasn't. :-)




Try Searching:
servers, voip, java, networking, microsoft ...
<Prev in Thread] Current Thread [Next in Thread>