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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With