Jan Doggen
Jan Doggen

Reputation: 9096

Why doesn't the Delphi compiler warn for a redefined constant?

A colleague of mine bumped into a constant that had suddenly 'changed value';
Turned out, it was redeclared:

unit Unit1;

interface

const
   MyConstant = 1;

implementation

end.

--

unit Unit2;

interface

const
   MyConstant = 2;

implementation

end.

--

Uses Unit1, Unit2;
// Uses Unit2, Unit1;

procedure TFrmRedefineConstant.FormShow(Sender: TObject);
begin
   ShowMessage('MyConstant: ' + IntToStr(MyConstant));
end;

This shows 2. If you swap the unit order in the Uses statement, it shows 1.

Fine, but why does the Delphi compiler not warn about the duplicate constant name (That would be very helpful)?
Is there anything I can do to enable warnings (does not look that way).

Upvotes: 9

Views: 384

Answers (1)

Mad Hatter
Mad Hatter

Reputation: 243

Because of Delphi documented scoping rules. From the Language Guide:

The order in which units appear in the uses clause determines the order of their initialization and affects the way identifiers are located by the compiler. If two units declare a variable, constant, type, procedure, or function with the same name, the compiler uses the one from the unit listed last in the uses clause. (To access the identifier from the other unit, you would have to add a qualifier: UnitName.Identifier.)

This is the expected behaviour since Turbo Pascal 4.0, which introduced units.

Upvotes: 6

Related Questions