[fpc-pascal] When is AnsiString not a good substitute for string?

J├╝rgen Hestermann juergen.hestermann at gmx.de
Sun Mar 21 16:45:51 CET 2010


> Frank Church schrieb:
> I recently posted a question about problems involving the use of
> string and AnsiString when converting a Delphi program. Are the some
> situations where substituting AnsiString for string will result in
> errors?

The string type is a generic type and can be ShortString or AnsiString (or other string types). A compiler switch then decides what type will be used.

AnsiString and ShortString are quite different. AnsiStrings are much more complex (and require more care when using them i.e. in records) but have a maximum length of 2 (or 4?) GB while ShortStrings are simpler (and therefore often faster) but limited to 255 bytes. 

When switching from one to the other type you may need to have a close look on how the strings are used in the program. Maximum length can be an issue. AnsiStrings are pointers so Sizeof() gives back 4 bytes while for ShortStrings it is the (maximum) size of the string plus 1 length byte. There are lots of such differences that *may* be a problem but not neccessarily are in all cases. 

There is also an (IMO) semantic logic error with AnsiStrings: Although they are pointers (pointing to the string) in most (but not all!) cases the compiler interprets them as the strings they points to. A := B is possible if A is a ShortString and B is an AnsiString (although A is not a pointer). It should have been A := B^ but Borland in their wise wisdom decided not to use this clear syntax. Though for low level routines like SizeOf and Fillchar it still uses the (correct) meaning of a pointer. So this may cause problems too.

Just check how both types are handled by the compiler and you will soon see where problems can arise.

For AnsiStrings see here: http://www.freepascal.org/docs-html/ref/refsu10.html




More information about the fpc-pascal mailing list