www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Forward reference to nested function not allowed?

reply "DLearner" <bmqazwsx123 gmail.com> writes:
Hi,

import std.stdio;
void main() {

    writefln("Entered");

    sub1();
    sub1();
    sub1();

    writefln("Returning");

    void sub1() {
       static int i2 = 6;

       i2 = i2 + 1;
       writefln("%s",i2);
    };
}

does not compile, but

import std.stdio;
void main() {
    void sub1() {
       static int i2 = 6;

       i2 = i2 + 1;
       writefln("%s",i2);
    };
    writefln("Entered");

    sub1();
    sub1();
    sub1();

    writefln("Returning");


}

compiles and runs as expected.

Is this intended?
May 31 2014
next sibling parent reply "Adam D. Ruppe" <destructionator gmail.com> writes:
On Saturday, 31 May 2014 at 16:18:35 UTC, DLearner wrote:
 Is this intended?
Yes, nested functions access local variables and thus follow the same order of declaration rules as they do; you can't use a local variable before it is declared so same with a nested function.
May 31 2014
parent Philippe Sigaud via Digitalmars-d-learn writes:
See:  http://dlang.org/function.html#variadicnested

The second example explains that nested functions can be accessed only
if the name is in scope.
May 31 2014
prev sibling parent Jonathan M Davis via Digitalmars-d-learn writes:
On Sat, 31 May 2014 16:18:33 +0000
DLearner via Digitalmars-d-learn <digitalmars-d-learn puremagic.com>
wrote:

 Hi,

 import std.stdio;
 void main() {

     writefln("Entered");

     sub1();
     sub1();
     sub1();

     writefln("Returning");

     void sub1() {
        static int i2 = 6;

        i2 = i2 + 1;
        writefln("%s",i2);
     };
 }

 does not compile, but

 import std.stdio;
 void main() {
     void sub1() {
        static int i2 = 6;

        i2 = i2 + 1;
        writefln("%s",i2);
     };
     writefln("Entered");

     sub1();
     sub1();
     sub1();

     writefln("Returning");


 }

 compiles and runs as expected.

 Is this intended?
Currently, you cannot forward reference a nested function. Kenji was looking into it recently, so maybe we'll be able to at some point in the future, but right now, we definitely can't. But even if we can in the future, I'd expect that you'd have to declare a prototype for the function to be able to use it before it's declared. In general though, I think that the only reason that it would really be useful would be to have two nested functions refer to each other, since otherwise, you just declare the nested function earlier in the function. - Jonathan M Davis
Jun 01 2014