Variable-Length Character, Graphic and UCS-2 Formats

Variable-length character fields have a declared maximum length and a current length that can vary while a program is running. The length is measured in single bytes for the character format and in double bytes for the graphic and UCS-2 formats. The storage allocated for variable-length character fields is 2 or 4 bytes longer than the declared maximum length, depending on how the VARYING, VARCHAR, VARGRAPH, or VARUCS2 keyword is specified for the field. The leftmost 2 or 4 bytes are an unsigned integer field containing the current length in characters, graphic characters or UCS-2 characters. The actual data starts at the third or fifth byte of the variable-length field. Figure 1 shows how variable-length character fields are stored:

Figure 1. Character Fields with Variable-Length Format
------------------------------------
   | current  | character data |
   | length   |                |
------------------------------------
     UNS(V)       CHAR(N)

 N = declared maximum length
 V = number of bytes specified for the length prefix

 V + N = total number of bytes

The unsigned integer length prefix can be either two bytes long or four bytes long. You indicate the size of the prefix by specifying 2 or 4 for the second parameter of the VARCHAR, VARGRAPH, or VARUCS2 keyword of a free-form definition, or using the parameter of the VARYING keyword of a fixed-format specification, either VARYING(2) or VARYING(4). If you specify VARCHAR, VARGRAPH, or VARUCS2 without a second parameter, or VARYING without a parameter, a size of 2 is assumed if the specified length is between 1 and 65535; otherwise, a size of 4 is assumed.

Figure 2 shows how variable-length graphic fields are stored. UCS-2 fields are stored similarly.

Figure 2. Graphic Fields with Variable-Length Format
------------------------------------
   | current  | graphic-data   |
   | length   |                |
------------------------------------
     UNS(V)       CHAR(N)

 N = declared maximum length = number of double bytes
 V = number of bytes specified for the length prefix

 V + 2(N) = total number of bytes
Note: Only the data up to and including the current length is significant.

You define a variable-length field by specifying the VARCHAR, VARGRAPH, or VARUCS2 keyword on a free-form definition, or by specifying A (character), G (graphic), or C (UCS-2) and the keyword VARYING on a fixed-form definition specification. It can also be defined using the LIKE keyword on a definition specification where the parameter is a variable-length field.

You can refer to external variable-length fields, on an input or output specification, with the *VAR data attribute.

A variable-length field is initialized by default to have a current length of zero.

You can obtain the address of the data portion of a variable-length field using %ADDR(fieldname:*DATA).

For examples of defining variable-length fields, see: