Puzzled by this behavior
Steven Schveighoffer
schveiguy at gmail.com
Wed Jun 22 13:05:11 UTC 2022
On 5/31/22 1:41 PM, Don Allen wrote:
> But
> ````
> import std.stdio;
>
> int main(string[] args)
> {
> void foo() {
> bar();
> }
> void bar() {
> writeln("Hello world");
> }
> foo();
> return 0;
> }
> ````
> gives the error
> ````
> (dmd-2.100.0)dca at pangloss.allen.net:/home/dca/Software/d_tests$ dmd test5.d
> test5.d(6): Error: undefined identifier `bar`
> ````
> This only works if you interchange the order of foo and bar, eliminating
> the
> forward reference.
A solution that comes from a post monkyyy posted about regarding
function overloading inside a function (also not allowed):
https://forum.dlang.org/post/uxycfvvbcogmbqrabghk@forum.dlang.org
```d
import std.stdio;
int main(string[] args)
{
template foo() {
void foo() {
bar();
}
void bar() {
writeln("Hello world");
}
}
foo();
return 0;
}
```
As long as you have one entry point to the set of functions, it works as
expected. If you need to call `bar` directly also, then you need to
change how the template works, and it's not any nicer than a struct. I
kind of like this solution, because it doesn't require making types, and
you don't have to call it differently.
-Steve
More information about the Digitalmars-d
mailing list