3.2.3 Short strings

A string declaration declares a short string in the following cases:

  1. If the switch is off: {$H-}, the string declaration will always be a short string declaration.
  2. If the switch is on {$H+}, and there is a maximum length (the size) specifier, the declaration is a short string declaration.

The predefined type ShortString is defined as a string of size 255:

 ShortString = String[255];

If the size of the string is not specified, 255 is taken as a default. The actual length of the string can be obtained with the Length standard runtime routine. For example in

{$H-}  
 
Type  
  NameString = String[10];  
  StreetString = String;

NameString can contain a maximum of 10 characters. While StreetString can contain up to 255 characters.

Remark: Short strings have a maximum length of 255 characters: when specifying a maximum length, the maximum length may not exceed 255. If a length larger than 255 is attempted, then the compiler will give an error message:

Error: string length must be a value from 1 to 255

For short strings, the length is stored in the character at index 0. Old Turbo Pascal code relies on this, and it is implemented similarly in Free Pascal. For Ansistrings this is not correct, and the compiler will give a warning if it detects this construct. For ansistrings, the length must be retrieved with the Length function or set with the SetLength function. Both functions work on shortstrings as well, and should be used for code that must compile in both Object Pascal as old Turbo Pascal mode.