Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Str in XE7 generates strange warning

Why does this code:

  w: word;
  s: String;
begin
  str(w, s);

generate this warning in XE7:

[dcc32 Warning] Unit1.pas(76): W1057 Implicit string cast from 'ShortString' to 'string'

Tom

like image 818
Tom Avatar asked Jan 30 '15 22:01

Tom


1 Answers

System.Str is an intrinsic function that dates from a byegone era. The documentation says this:

procedure Str(const X [: Width [:Decimals]]; var S: String);

....

Notes: However, on using this procedure, the compiler may issue a warning: W1057 Implicit string cast from '%s' to '%s' (Delphi).

If a string with a predefined minimum length is not needed, try using the IntToStr function instead.

Since this is an intrinsic, there is likely something extra going on. Behind the scenes, the intrinsic function is implemented by a call to an RTL support function that yields a ShortString. Compiler magic then turns that into a string. And warns you of the implicit conversion. The compiler magic transforms

Str(w, s);

into

s := _Str0Long(w);

Where _Str0Long is:

function _Str0Long(val: Longint): _ShortStr;
begin
  Result := _StrLong(val, 0);
end;

Since _Str0Long returns a ShortString then the compiler has to generate code to perform the implicit converstion from ShortString to string when it assigns to your variable s. And of course it's then natural that you see W1057.

The bottom line is that Str only exists to retain compatibility with legacy Pascal ShortString code. New code should not be calling Str. You should do what the documentation says and call IntToStr:

s := IntToStr(w);

Or perhaps:

s := w.ToString;
like image 88
David Heffernan Avatar answered Oct 30 '22 14:10

David Heffernan