Yet another surprise from Delphi compiler

Build and run the following console app:

program ItWorks;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TTest = record
    FData: Integer;
  end;

procedure DoTest(const S: string);
begin
  Writeln(TTest(S).FData);
end;

begin
  try
    DoTest('123');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

I tested in Delphi XE and Delphi 10.1 Berlin, it compiles and even works!

Advertisements

5 thoughts on “Yet another surprise from Delphi compiler

  1. What exactly is your definition of “works” in this context? You are doing a hardcast of a type with the same size, of course that “works” – by the way, compile with Win64 and watch the compile error (hint: use NativeUInt)

    • I did not define explicit conversion for TTest type, so I thought the code should not compile. I noticed this feature when I removed explicit conversion from string operator from my record type, and found that the code that used explicit conversion still compiles. Thank you, I see now what the cast is really doing.

  2. Of course it works. You’re lying to the compiler. You’ve told the compiler, “Yes, I know S is a string, but I want you to treat it as a TTest record.” The compiler happily acquiesces to your demands and builds the code. As stated previously, the fact that this works in 32bit is by pure happenstance. Try it with 64bit, and watch your world fall apart.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s