SIZEOF function

Purpose

Return the total or physical length of any PowerBASIC variable.

Syntax

x& = SIZEOF(target)

Remarks

Particularly useful for determining the maximum length of a fixed-length string, ASCIIZ string, or User-Defined Type.  It provides similar functionality to LEN, which returns the current length of a data item.

target can be the name of any variable type (fixed-length string, ASCIIZ string, User-Defined Type (UDT) variable or definition, etc).

When measuring the size of a padded (aligned) UDT variable or definition with the SIZEOF (or LEN) statement, the measured length includes any padding that was added to the structure.  For example, the following UDT structure:

TYPE LengthTestType DWORD

  a AS INTEGER

END TYPE

...

DIM abc AS LengthTestType

x& = SIZEOF(abc) ' or use SIZEOF(LengthTestType)

Returns a length of 4 bytes in x&, since the UDT was padded with 2 additional bytes to enforce DWORD alignment.  Note that the SIZEOF of individual UDT members returns the true size of the member without regard to padding or alignment.  In the previous example, SIZEOF(abc.a) returns 2.

When used on a dynamic (variable length) string, SIZEOF returns 4, which is the size of the string handle.  To obtain the length of the string data in the dynamic string, use the LEN function.  SIZEOF also returns 4 for pointer variables, since a pointer is always stored as a DWORD.

Pointers

When used with a dereferenced pointer (i.e., SIZEOF(@p), SIZEOF returns the size of the pointer target variable type, as defined in the DIM x AS y PTR [* pSize] statement.

For example, with a dynamic string pointer, SIZEOF returns 4.  If the pointer target is a fixed-length string, UDT, Union, or ASCIIZ string, SIZEOF returns the size of the target data structure.  However, if the pointer is declared to reference an ASCIIZ with no specific target size (i.e., DIM a AS ASCIIZ PTR), SIZEOF returns 0.

Likewise, if SIZEOF is used on a BYREF ASCIIZ string that does not have an explicit length specification, SIZEOF will also return 0.  For example:

SUB ProcessData(BYREF szText AS ASCIIZ)

  ' Within this Sub, SIZEOF(szText) will return 0 because there is no explicit length specification

See also

DIM, LEN

Example

DIM Strval AS ASCIIZ * 10

Strval = "test"

' SIZEOF(Strval) = 10, LEN(Strval) = 4

 

DIM Intval AS QUAD

Intval = 1

' SIZEOF(Intval) = 8, LEN(Strval) = 8

 

DIM CustName AS STRING

CustName = "Fred Dagg"

' SIZEOF(CustName) = 4, LEN(CustName) = 9

 

UNION Arrs

  m1(1 TO 1024) AS BYTE

END UNION

DIM p1 AS STRING PTR

DIM p2 AS STRING PTR * 1024

DIM p3 AS Arrs PTR

DIM p4 AS ASCIIZ PTR

DIM p5 AS ASCIIZ PTR * 64

' Results of SIZEOF on these pointers:

' SIZEOF(p1) = 4, SIZEOF(@p1) = 4

' SIZEOF(p2) = 4, SIZEOF(@p2) = 1024

' SIZEOF(p3) = 4, SIZEOF(@p3) = 1024

' SIZEOF(p4) = 4, SIZEOF(@p4) = 0

' SIZEOF(p5) = 4, SIZEOF(@p5) = 64

' SIZEOF(Arrs) = 1024