Pointers in BASIC

BASIC, as Rodney Dangerfield would have said, “don’t get no respect.” Even when using modern dialects like FreeBASIC, which allow custom user types, modern-style functions and subroutines, encapsulation, and more, there’s still very much a “Real Men Program In C” attitude.

C is deservedly famous and influential, of course, but it’s often tedious to write small, proof-of-concept programs in C. If a new idea about, say, cellular automata strikes you, it’s very easy to write a few lines of BASIC code and be testing it — in full-color HD.

But still, C proponents say, it’s a “toy” language. It doesn’t have pointers or linked lists or all that.

Except — it does. In FreeBasic, at least, the familiar malloc() and sizeof() functions are available, and memory truly can be dynamically allocated, deallocated, and manipulated as pointers.

Here is a short example that demonstrates creating and printing out a simple linked list in FreeBASIC. Memory is dynamically allocated and user type fields are accessed with the -> operator, just as in C.

'Pointers in FreeBASIC
 'Example: Create and print out a short linked list

'M. Eric Carr / Paleotechnologist.Net
 'Contact: eric (at) the above domain

'Define a simple user type
 type listItem
 payload as double
 link as listItem ptr '"next" is a keyword in BASIC; we can't use it.
 end type

dim as listItem ptr head, current
 dim as integer n

'Teach FreeBASIC about NULL
 const NULL = 0

'Set up the first item in the list manually
 head = allocate(sizeof(listItem))
 current = head
 current->payload = 0
 current->link = NULL

'Use a for loop to add nine more items to the list
 for n=1 to 9
 'Starting conditions: current points to last item in the list.
 current->link = allocate(sizeof(listItem))
 current = current->link
 current->link = NULL 'For safety
 current->payload = n^2
 next n

'Read them back using a while loop, looking for the NULL at the end
 current = head
 while current <> NULL
 print current->payload
 current = current->link
 wend

'Done. Wait for a keypress before exiting.
 sleep

(Don’t tell the use-C-or-die types, but FreeBASIC can use inline x86 assembly, too.)

This entry was posted in BASIC, C, Coding, HOW-TO. Bookmark the permalink.

Leave a Reply