Domanda

I've been programming Delphi for five or six years now and I consider myself fairly good at it, but I stumbled across a behavior recently which I couldn't really explain. I was writing a simple linked list, let's call it a TIntegerList. The example code below compiles correctly:

type
  PIntegerValue = ^TIntegerValue;

  TIntegerValue = record
    Value: Integer;
    Next: PIntegerValue;
    Prev: PIntegerValue;
  end;

However, the code below does not (saying TIntegerValue is undeclared):

type
  PIntegerValue = ^TIntegerValue;

type  
  TIntegerValue = record
    Value: Integer;
    Next: PIntegerValue;
    Prev: PIntegerValue;
  end;

How exactly is the "type" keyword handled in Delphi? What is the syntactical meaning of having several types declared under one "type" keyword, compared to having one "type" per type? Alright, that was confusing, but I hope the code example helps explain what I mean. I am working in Delphi 2007.

È stato utile?

Soluzione

Logically there's no need to use the type keyword when the code is already part of an existing type declaration section. So,

type
  TRec1 = record
  end;

  TRec2 = record
  end;

produces types that are indistinguishable from

type
  TRec1 = record
  end;

type
  TRec2 = record
  end;

However, as you have discovered, the compiler has a limitation that requires all forward declarations to be fully resolved before the end of the section where the forward declaration was introduced.

There's no particular reason that it has to be that way. It would be perfectly possible for the compiler to relax that limitation. One can only assume that a compiler implementation detail, probably originating a very long time ago, has leaked into the language specification.

Altri suggerimenti

This pure standard Pascal. Since Pascal compilers are usually one-pass and there is no forward declaration for types, this feature was defined in the original Pascal by N. Wirth to allow such 'recursive' types for e.g. linked lists etc.

I have already given a comment but it is to be peer-reviewed. This is rather in effective. Therefore here is another answer. This may be merged or what ever you want.

In "Algorithms + Data Structures = Programs" Wirth gives an example in "Program 4.1 Straight List Insertion"

type
  ref  = ^word;
  word = record
           key: integer;
           count: integer;
           next: ref
         end;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top