Search code examples
qbasic

How to declare any-range string element inside an user-defined type in QBasic?


I'm learning QBasic and found an user-defined type example code in a documentation. In this example there's a string element inside an user-defined type, and that string doesn't have a length defined.

However my compiler throws the exception "Expected STRING * on..." for this example. Test-case defining the string length:

TYPE Person
    name AS STRING * 4
END TYPE

DIM Matheus AS Person:
Matheus.name = "Matheus":

PRINT Matheus.name:

It logs "Math", expected "Matheus". Is there a way to allow any range for this string?

Note: I'm using QB64 compiler


Solution

  • No, there is not a way to use a variable-length string, even with QB64. You might look into FreeBASIC if you want this feature since it offers it.

    TYPE creates a record type with the specified fields, and records have a fixed length. Look at the OPEN ... FOR RANDOM specification:

    OPEN Filename$ FOR RANDOM AS #1 [LEN = recordlength%]
    
    • recordlength% is determined by getting the LEN of a TYPE variable or a FIELD statement.
    • If no record length is used in the OPEN statement, the default record size is 128 bytes except for the last record.
    • A record length cannot exceed 32767 or an error will occur!

    TYPE was never intended to contain strings that are dynamically sized. This allows a developer to keep record sizes small. If you had an address book, for example, you wouldn't want people's names to be too large, else the address book wouldn't fit in memory.

    QB64 didn't remove that restraint, probably to keep things compatible with older QBASIC code since the original goal was to preserve compatibility.