You wondered why pointers are necessary; here are two examples.
1)
I made a GUI library (which I will be posting soon), and it has a function that will say which button or text box (or any other object in the library) was last clicked by the user.
I could have it return the label of the object:
(note this is not exactly the real code I use for the library)
If igui.get_last_click = "Quit" Then System 'clicked the quit button
The problem is, some buttons don't need labels, some labels are always changing, some two buttons might have the same label, and string comparisons are slow.
So instead, I use pointers:
If igui.get_last_click = @my_quit_button Then System 'clicked the quit button
I can use this same code even if my_quit_button is a text box instead of a button.
2)
INIMe
This object / class I wrote uses pointer for two reasons:
2.1)
Firstly, it keeps a list of variables, but some of them are numbers, and others are strings. You cannot store numbers and strings in the same array:
mydata(1) = 55: mydata(2) = "Hi, forum!" 'not possible if mydata() is an array of a built-in type
The only way to keep both numbers and strings in the same array is with pointers:
Code: Select all
variable_pointers(variable_total) = @variable
variable_types(variable_total) = variable_enum.vdouble
In INIMe, this only requires a pointer, and a variable to specify whether the pointer points to a number (integer, single, or double) or string.
If you did this without pointers, you would need a variable for the Integer, Single, Double, and String, and another variable to state whether the element of the array is supposed to be a number or string. This would take about twice as much memory and probably would be slower.
2.2)
In the example, you can see that even though you want y to equal x, they are not equal after x changes:
Code: Select all
'Code without pointers
Dim as Integer x, y
x = 5
y = x
x = 6
Print x, y
Sleep
Sometimes you will need y to equal x, even if x changes. You can do this with pointers:
Code: Select all
'Code with pointers
Dim as Integer x
Dim as Integer Ptr y
x = 5
y = @x
x = 6
Print x, *y
Sleep
Notice that, even though x changed in
x = 6, x and *y are still equal.
(This is because, x and *y access the exact same memory.)
I used this in INIMe, where y (the pointer) is part of the object, and is not managed directly by programmer who uses INIMe.
In this line, INIMe sets a pointer to point to
v1:
datadb.add("variable 1", v1)
Then later in the program, the programmer might type
datadb.save to save variable
v1 to a file.
V1 might change between those two lines:
Code: Select all
datadb.add("variable 1", v1)
v1 = 999
datadb.save
For this object to work, datadb (the INIMe object) has to save "999" to the file, not the value of
v1 when the line
datadb.add("variable 1", v1) was run. This is only possible with pointers.
... And that's why pointers are necessary.
BTW, feel free to post this in QB Express. ;-)