Forward declaration issue

Artur Skawina via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Dec 4 01:51:30 PST 2015


On 12/04/15 09:12, Andre via Digitalmars-d-learn wrote:
> Hi,
> 
> I have a strange issue with following coding.
> 
> void baz(); // forward declaration
> 
> void foo()
> {
>     void bar()
>     {
>         baz(); // (1) without f.d. syntax error
>     }
>     
>     void baz()
>     {
>         bar();
>     }
>     
>     baz(); // (2) No linker error if line is removed
> }
> 
> void main()
> {
>     foo();
> }
> 
> Without the forward declaration, there is a syntax error at (1)
> With the forward declaration there is no syntax error but
> a linker error at (2). This linker error disappears if line at (2)
> is removed.
> It looks like a bug, is it?

No, it's how D is designed -- inside functions the order of
declarations matters (and forward declarations don't work).

Your version wrongly declares another `baz` at module scope,
and, as there's no definition, you end up with the linker error.

Two workarounds:

1) Templatize the functions:

   void foo()
   {
      void bar()()
      {
          baz();
      }
    
      void baz()()
      {
          bar();
      }
    
      baz();
   }

2) Use a struct:

   void foo()
   {
      struct Hack {
         void bar()
         {
             baz();
         }

         void baz()
         {
             bar();
         }
      }

      Hack hack;

      hack.baz();
   }

artur


More information about the Digitalmars-d-learn mailing list