43
74
75
76
77
EndIf
Sleep
End
Listing 10.4: type-ptr.bas
Analysis:
This version of the program has a few modifications from the previous
versions, but overall it is the same program. Line 3 defines a return for the InitDept
function. If the functions returns this code, the department id is valid; if the function does
not return this code, the department id is invalid. The type definitions are the same as
used previously, but the function in line 20 has changed.
The function now returns an integer value, and there are two parameters, a
department id and a pointer to the DepartmentType. Line 21 dimensions and initializes
the function return value to deptok. If there are not errors, this value will be returned. If
the deptid is invalid, the Case Else will set the return value to Not deptok (-1) in line 36.
This is a good technique to return boolean values from a function. By initializing the
return variable to the “ok” status, you only need to set the variable to the “not ok” status,
if an error occurs. Less typing, less code and fewer chances of introducing bugs into the
program.
In the individual Case blocks, the arrow notation is used to access the individual
fields of the type pointer. The -> automatically dereferences the pointer for you, making
it easier to manipulate the individual fields within the type. Line 39 returns the success
code of the function. You don't need to return any type information, because the function
is actually updating the external department type variable through the pointer.
Line 44 dimensions a DepartmentType pointer. Which is initialized in line 47.
Remember that Callocate allocates a memory segment, clears the segment and then
returns the address of the segment which is stored in the variable tmpDept. In line 49 the
InitDept function is called inside an If statement. If the function fails, that is returns Not
deptok, then the program deallocates the pointer and prints an error message. If the
function succeeds, that is returns deptok, then the Employee type is initialized and the
data is printed to the screen. Notice in line 59 that the program is still using a type
assignment, but because tmpDept is a pointer, the dereference operator must be used.
Line 62 shows the power of using pointers as intermediate data structures. Once
the department data is in the Employee type, you don't need the department type
reference. Line 62 deallocates tmpDept, freeing the memory it was using. There is no
sense in wasting memory on data structures that you only use for a very short time.
The rest of the program is identical to the previous programs.
When you run this program you should again see the same output as the previous
programs.
127