02-04-2024, 08:59 PM
With Option Explicit, you must declare the variable before you use it -- IN SCOPE. << That's the only thing you need to remember.
With the above, you can see that where we declare our variable really doesn't matter -- as long as it's BEFORE we use that variable.
The only real thing to note is that DIM works in a top-down approach, much as DEFtype and _DEFINE statements do. It doesn't follow program flow; it only follows line numbers.
For example:
Now, with the simple code above, the program flow starts at the option explicit, jumps into the GoSub foo, there it sees a DIM A AS INteger, sets a value for A, returns, and then ERROR ERROR ERROR ERROR ERROR!!! UNDECLARED VARIABLE!!!
That DIM A comes *AFTER* the PRINT A, if you read the code in a simple Top-Down approach, ignoring jumps, branches, and such. That doesn't work. You've got to place that DIM *before* you ever use the variable/array, or else it's just going to wrror out on you.
This is all due to the nature of how DEFtype statements and _DEFINE have worked since the early days of GWBASIC, and as we work on emulating QB45(which used the same methods), it's just the way things work.
Code: (Select All)
Option _Explicit
Dim A As Integer 'declare A
Print 1 'main module junk
Sleep
Cls
Input A 'use A. No issues
GoSub foo 'a gosub to a label, with the label defined later. No issues.
End
foo:
Dim B As Single 'We declare B in the subroutine. no issues.
B = 1.23
Print B
Return
Sub foo2
Dim C As Long 'here we declare C in the SUB, at the top of the code. No problem.
C = 123456
Print C
GoSub foo3
Exit Sub
foo3:
Dim D As Double 'same with declaring D inside the subroutine inside the SUB. No problem.
D = 1.23456789
Print D
Return
End Sub
With the above, you can see that where we declare our variable really doesn't matter -- as long as it's BEFORE we use that variable.
The only real thing to note is that DIM works in a top-down approach, much as DEFtype and _DEFINE statements do. It doesn't follow program flow; it only follows line numbers.
For example:
Code: (Select All)
Option _Explicit
GoSub foo
Print A
foo:
Dim A As Integer
A = 123
Return
Now, with the simple code above, the program flow starts at the option explicit, jumps into the GoSub foo, there it sees a DIM A AS INteger, sets a value for A, returns, and then ERROR ERROR ERROR ERROR ERROR!!! UNDECLARED VARIABLE!!!
That DIM A comes *AFTER* the PRINT A, if you read the code in a simple Top-Down approach, ignoring jumps, branches, and such. That doesn't work. You've got to place that DIM *before* you ever use the variable/array, or else it's just going to wrror out on you.
This is all due to the nature of how DEFtype statements and _DEFINE have worked since the early days of GWBASIC, and as we work on emulating QB45(which used the same methods), it's just the way things work.