Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between one and many "type" blocks in Delphi

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.

like image 760
kling Avatar asked Mar 11 '13 10:03

kling


2 Answers

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.

like image 160
David Heffernan Avatar answered Nov 15 '22 07:11

David Heffernan


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.

like image 27
gammatester Avatar answered Nov 15 '22 05:11

gammatester