Search code examples
stringdelphidelphi-xe7

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


Solution

  • 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;