Option base 0

Discussion of issues related to writing ZBasic applications for targets other than ZX devices, i.e. generic targets.
Post Reply
stevech
Posts: 715
Joined: 22 February 2006, 20:56 PM

Option base 0

Post by stevech »

I'm probably missing a concept here, but below, txPayload is supposed to be a pointer to a byte array with the first element being 0

Code: Select all

Option Base 0
...
public txPayload() as byte byref
...
txPayload(0) = x
Compiler says invalid index in the above if 0 is used, but 1 yields no error.
The value of txPayload varies at run-time.
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: Option base 0

Post by dkinzer »

stevech wrote:txPayload is supposed to be a pointer to a byte array with the first element being 0
The Option Base directive only affects the number of elements that are allocated for an array whose lower bound is not specified when the array is defined. In all other cases, the lower bound of an array of elements is taken to be 1.

Consider this ZBasic code:

Code: Select all

Public txPayload() as Byte ByRef
Dim array1(0 to 19) as Byte
Dim array2(-5 to 14) as Byte
Dim x as Byte

Sub Main()
    txPayload.DataAddress = array1.DataAddress
    txPayload(1) = x
    txPayload.DataAddress = array2.DataAddress
    txPayload(1) = x
End Sub
The C code generated for this is:

Code: Select all

static uint8_t mzv_array1[20];
static uint8_t mzv_array2[20];
static uint8_t mzv_x;

uint8_t *zv_txPayload;

void
zf_Main(void)
{
    zv_txPayload = (uint8_t *)(uint16_t)mzv_array1;
    zv_txPayload[1 - 1] = mzv_x;
    zv_txPayload = (uint8_t *)(uint16_t)mzv_array2;
    zv_txPayload[1 - 1] = mzv_x;
}
You can see, then, that referring to element(1) accesses the first element of the array irrespective of the bounds used to define it.
- Don Kinzer
stevech
Posts: 715
Joined: 22 February 2006, 20:56 PM

Post by stevech »

I see. I was confused because the manual says Option Base 0 controls whether array elements index beginning with 0 vs. 1. That's how I read
The Option Base directive is provided to allow you
to specify that the default array base is either 0 or 1...
I recall in VB6, Option Base 0 meant 0 is the index of the first element. So the ByRef (pointer) would use the same convention (base 0), it seemed to me.

It's still a bit fuzzy.
Post Reply