Calling nested function before declaration

nkm1 t4nk074 at openmailbox.org
Fri Sep 28 02:25:09 UTC 2018


On Wednesday, 26 September 2018 at 22:46:21 UTC, Jonathan wrote:
> This code fails to compile: ("undefined identifier fun")
> void main() {
>     fun();
>     void fun() {}
> }
>
> Having the call after the declaration works:
> void main() {
>     void fun() {}
>     fun();
> }
>
> Is this how it is intended to work?
>
> It seems goofy that this works:
> void main() {
>     void fun2() {}
>     void fun() {
>          fun2()
>     }
>     fun();
> }
>
> But this fails to compile: ("undefined identifier fun2")
> void main() {
>     void fun() {
>          fun2()
>     }
>     void fun2() {}
>     fun();
> }
>
> What if I wanted this?
> void main() {
>     void fun2() {fun();}
>     void fun() {fun2();}
>     fun();
> }
>
> I can't see how the current behavior is at all better or to be 
> preferred unless it is faster to compile?  What is the reason 
> for it being how it is?

One of the reasons is consistency perhaps. Functions are not 
different from other identifiers:

void fun1()
{
     writeln(x);
}

int x = 1;

void fun2()
{
     writeln(y); // fails ("undefined indentifier y")
     int y = 2;
}


More information about the Digitalmars-d mailing list