Delphi - System.Copy Best Practices

From my knowledge, line 1 is based on Delphi, position 0 is reserved for length. I am in charge of a huge application written in D5 and D2006 that uses the copy function, copying from index 0, and several colleagues are also coding this way at this point. Since this is a Delphi "magic" feature, I believe that even though Copy is used to copy the string from index 0, behind the scenes it copies it from position 1.

It is good practice for me to copy the string from 1st position, not from position 0, even the result is the same.

Now, my question is, could the application be affected when transferred to another version of Delphi using the copy function from position 0 instead of being used to copy from position 1?


source to share

1 answer

Delphi RTL ignores you when passing 0 as a parameter Index

in Copy

for a string. When you pass 0 or less for Index

, RTL uses the value 1

. So what you are doing is the benignity that there is no discernible difference in behavior between passing 1 or any value less than 1. However, of course, it is confusing to use 0

as a string index in Delphi, and I would recommend not doing that.

In pseudocode, the implementation Copy

starts like this:

function Copy(s: string; Index, Count: Integer): string;
  if Index<1 then
    Index := 1;
  dec(Index);//convert from 1-based to 0-based indexing


In fact, the actual implementation is a little more complicated, but the pseudocode above gives the correct semantics.

Your comment about the length stored at index 0 is correct for old-style short strings. But this is not the case for long lines. In fact, it was this fact that led to a rather strange situation where strings are 1-based, but dynamic arrays, lists, etc. Based on 0.



All Articles