Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I explicitly declare my variables in VB6

I'm writing some code in Visual Basic 6 and I have noticed that I don't even need to declare variables for things to work.

The following (explicit declaration):

Dim foo As String
foo = "Bar"

Seems to work just as well as this (implicit declaration):

Dim foo
foo = "Bar"

Or this (no declaration):

foo = "Bar"

I know in C# I need to declare a variable before I use it, and that implicit and explicit declarations are both acceptable. I also know that in Python, you don't declare your variables at all before you use them.

In regards to Visual Basic 6 (and by extension VBA) which is proper?

Thanks

like image 748
JMK Avatar asked Apr 18 '12 17:04

JMK


2 Answers

It's a good HABIT.

There is a VB option called Option Explicit. With that set to ON, then VB forces you to declare a variable before you use it: no more

foo = "Bar"

That helps with mistyping the variable name later in your code... without that, you can typso the variable name, your program compiles but won't work, and it's HARD to dig that out.

like image 108
Willow Anne Avatar answered Sep 22 '22 10:09

Willow Anne


In Tools/Options, Editor tab, check the Require Variable Declaration checkbox. This will automatically add Option Explicit to every new code module.

enter image description here

I would say this is more than a best practice; I think of it as a requirement for programmer sanity. The setting is persistent; once set, it stays enabled. Microsoft made it an option because some older versions of VB didn't have the feature, which also explains why it was disabled by default.

like image 39
JeffK Avatar answered Sep 19 '22 10:09

JeffK