Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 289
Jan Doggen Avatar asked Jun 25 '13 08:06

Jan Doggen


1 Answers

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.

like image 183
Mad Hatter Avatar answered Oct 23 '22 10:10

Mad Hatter