Nested function requires forward declaration?
Chris Katko
ckatko at gmail.com
Thu Apr 14 08:55:25 UTC 2022
Using DMD. v2.098-beta-2
Not sure if right terminology. But I just wrote a nested function
that uses a variable outside its body. The capture (right term?)
is obvious where the invocation is. However, I have to move the
declaration of the variable to above the nested function for it
to compile.
Here is the code that wont compile:
````D
void execute()
{
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}
ALLEGRO_EVENT event;
// later
isKey(ALLEGRO_KEY_W);
// main.d(491): Error: undefined identifier `event`
````
This however, will compile:
````D
void execute()
{
ALLEGRO_EVENT event; // <--Only change
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}
// later
isKey(ALLEGRO_KEY_W);
````
It appears the nested function's variable capture depends on
forward declaration (the right term?). Whereas, I was under the
impression most/all of D worked on a multiple pass compilation so
the order of declarations shouldn't matter.
Is this a D spec, or a compiler parsing error/oversight?
I guess if I had two different variables called event, this could
become confusing code to read except that, mentally these should
still link up, right?
Hypothetical:
````D
void execute()
{
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}
{
ALLEGRO_EVENT event;
isKey(ALLEGRO_KEY_W);
} //lets say this does some memory housekeeping/deleting so
that's why we use scope
{
ALLEGRO_EVENT event; //new 'event', same name, new memory
isKey(ALLEGRO_KEY_W);
}
}
````
in this case, 'event' under-the-hood could be renamed, say,
"event2" and have the same expected compile time symbol linking
occur. The second isKey call is obviously connected to the second
'event' variable.
I imagine this is a really odd edge case but it's piqued my
interest.
More information about the Digitalmars-d-learn
mailing list