%STR works in both directions. As an expression it reads the characters a pointer addresses, up to but not including the first null byte. As the target of an assignment it stores a value and adds the null terminator:
DCL-S p POINTER;
p = %ALLOC(20);
%STR(p : 20) = 'abcdef'; // storage now holds 'abcdef' + a null byte
DSPLY %STR(p); // abcdef
The store works as follows:
- The length is required when
%STRis the assignment target - it is what bounds the write. Omitting it is a compile-time error. - One byte of the stated length is the terminator. With a length of N, at most N-1 characters of the value are stored; a longer value is truncated.
%STR(p : 4) = 'abcdef'storesabc. - Only the value and its terminator are written. Bytes past the terminator keep whatever they held - the length bounds the write, it does not fill it.
- The value is stored verbatim, including blank padding. Assigning a
CHAR(10)field holding'abc'stores ten characters, not three. Use%TRIMRif you want the padding dropped. - A length below 1 leaves no room even for the terminator and fails at runtime with RPG status
00222, as does a write that would run past the end of the storage the pointer addresses.
The pointer operand is any pointer expression, so it composes with pointer arithmetic - %STR(p + 3 : 10) = 'xy' stores three bytes in.