Question

From my knowledge strings are 1 based in Delphi, 0 position is reserved for the length. I am in charge of an huge application written in D5 and D2006, which is using the copy function by copying from the 0 index, and several colleagues are also coding in this way in this moment. Because this is a Delphi 'magic' function, I believe that even if Copy is used to copy the string from 0 index, behind the scenes it copies it from the position 1.

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

Now, my question is, can be the application affected when passing to other Delphi version by using the copy function from 0 position instead of be used to copy from 1 position?

Was it helpful?

Solution

The Delphi RTL ignores you when pass 0 as the Index parameter to Copy for a string. When you pass 0 or less for Index, the RTL uses a value of 1. So what you are doing is benign in that there are no observable differences in behaviour between passing 1 or any value less than 1. However, it is certainly confusing to use 0 as a string index in Delphi and I would recommend not doing so.

In pseudo-code, the implementation of Copy starts like this:

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

In fact the actual implementation is a little more complex, but the above pseudo-code gives the correct semantics.

Your comment about the length being stored at index 0 is true for old style short strings. But it is not true for long strings. In fact it was this very fact that led to the rather odd situation whereby strings are 1-based, but dynamic arrays, lists etc. are 0-based.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top