The BASED keyword declares a variable whose storage is accessed through a basing pointer:
DCL-S pField POINTER;
DCL-S wField CHAR(10) BASED(pField);
A BASED variable has no storage of its own - it is a typed view over the bytes the basing pointer addresses. Its storage therefore comes from setting the pointer (for example with ALLOC); a BASED variable must not be referenced before its pointer is set. Doing so faults at runtime, just as it does on IBM i (pointer not set).
Because all BASED variables on a pointer read and write the same bytes, they overlay one another at that address:
- Two variables of the same type see the same value - a write through one is visible through the other.
- Two variables of different types reinterpret the same bytes, exactly like an
OVERLAY. For example, a 4-byte integer and a 2-byte integer based on the same pointer share storage, so the 2-byte variable reads the high-order half of the 4-byte value (IBM i stores integers big-endian).
REALLOC resizes that storage in place, preserving the bytes; reading a BASED variable beyond the current allocation faults.
The BASED keyword and POINTER type are supported in both free-format (DCL-S) and fixed-format D-specs (column 40 = *). BASED variables may be character (fixed or varying), packed-decimal, zoned-decimal, binary, integer, unsigned, float, indicator, date, time, or timestamp types. A based date/time/timestamp is stored as its *ISO character form (10, 8, and 26 bytes respectively).