This seems like an awfully basic question, but I still can't find an answer for it.
In VBScript, is there any harm in declaring the same scalar variable with the Dim statement more than once?
I'm working on some related projects and developing some code pieces I'd like to reuse. However, I'm slightly concerned if there's a problem with using code that uses the same variable name twice, like so:
Dim i
for i = 1 to Count
'* doin' somethin' here
next
Dim i
for i = 1 to UnrelatedOtherCount
'* doin' somethin' different yo
next
It's not just iteration loop variables, either; I may have multiple places in a script where regexes are used. If my script uses two sections of code being re-used, and each of them uses a "patternString" variable and starts by declaring the variables:
'* first section of code from the folder
Dim objPersonRegex, patternString
Set objPersonRegex = new RegExp
...
'* a completely different section of code
Dim objBuildingRegex, patternString
Set objBuildingRegex = new RegExp
My instinct is to say that it shouldn't be a problem, that Dim just creates a variable of the given name if it doesn't already exist, and if it does, just goes on because what it was told to do is done. But is this actually the case? In case it matters, these are scripts running on Windows Script Host.
(To clarify what I'm worried about, I'm not worried at all about the value of the variable getting clobbered. If I need to retain the value of the variable, I'll save it in a different variable, one with a unique name.)
All my attempts to look up the answer myself have failed; they only return information about declaring more than one variable on a line, and using ReDim on arrays.
Is it harmful to Dim a variable more than once?
It is impossible to Dim a variable more than once. Neither not using Option Explicit
nor (mis)using On Error Resume Next
will get more than one Dim for the same variable (name) in the same compilation unit past the 'compiler'.
Dim doesn't just create then re-create the variable. It allocates a memory address for it. So, assuming you are coding with OPTION EXPLICIT turned on, it won't let you even do that.
However... What you're showing there as an example is not declaring the variable again. Not the same way, at any rate. That's not "dimmed". It's just temporarily used and thrown away when it's done. So, in that respect, you are doing it the right way.
If you were to create a new variable for every little thing that ran in a loop, when they don't interefere with each other, that becomes rather inefficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With