[fpc-pascal] Strings greater than 255 characters

Tomas Hajny XHajT03 at hajny.biz
Tue Dec 19 13:27:34 CET 2023


On 2023-12-19 12:36, James Richters via fpc-pascal wrote:


Hello James,

> I keep getting bit by using STRING variables then trying to store more
> than 255 characters.
> 
> My typical way to fix this is to just change it to an ANSISTRING.
> 
> I'm wondering if there is any reason not to do this the other way
> around and just go through
  .
  .

You may be surprised, but FPC (and even earlier also Delphi) provides 
you with multiple ways allowing you to use variables declared as 
"string" without length limits (i.e. using type ansistring or 
unicodestring underneath). There are compiler directives {$H+} and 
{$UNICODESTRINGS} doing exactly that, and there are also modes {$MODE 
DELPHI} and {$MODE DELPHIUNICODE} which (among others) trigger the 
previously mentioned compiler directives (the difference is that the 
modes have wider impact, not only the underlying type used for 
variables, parameters, etc., of type string).

In order to answer you question about potential reasons for not using 
ansistring or unicodestring for everything, it's useful to understand 
the associated differences:

1) Ansistring and Unicodestring are reference counted. This brings some 
computational overhead potentially impacting performance - this may not 
be important in many cases, but there are also cases for which this may 
be very important.

2) Ansistring and Unicodestring are technically pointers to structures 
allocated on the heap rather than directly storing the string itself 
with preallocated number of characters. There are scenarios for which 
this difference is important (e.g. when interfacing with operating 
system API calls or 3rd party code in general).

3) There are some other smaller differences impacting compatibility with 
code designed to work with type shortstring (e.g. related to used 
character sets etc.).

Tomas


More information about the fpc-pascal mailing list