Link to home
Start Free TrialLog in
Avatar of calacuccia
calacucciaFlag for Belgium

asked on

Simple Declaration Question

<ADD-ON 03:24 AM>

If you start to read this question, please look at the comment from pritam_dewan, that is the kind of information I am looking for.

"Declaring by Dim statement will indicate the compiler to allocate approriate memory for the variable
before assingment which is more reliable and faster,then without declaring it,will make the compiler
to identify the data type and then allocate the memory and then assign the value.So use of Dim is always
better."

Thanks
calacuccia

<END OF ADD-ON>


Hi,

I have a lot of string variables in a module. What's the use of declaring them, stating

- Option Explicit is not used
- String variables are string$, string2$ ....

Is there any use to add a declaration line

Dim string$, string2$

in the beginning of the module?

calacuccia
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

Hi calacuccia,

Option Explicit is use to force explicit declaration of all variables. Attempting to use an undeclared variable causes an error at compile time, and it is used at the module level only.

Example:

Option explicit    ' Force explicit variable declaration.
Dim MyVar    ' Declare variable.
MyInt = 10    ' Undeclared variable generates error.
MyVar = 10    ' Declared variable does not generate error.

Avatar of calacuccia

ASKER

Hi Ryan,

I know what Option Explicit means.

I am not using it for this project. My question is what the use is of declaring a string variable which already implicitely by the name choice is a string variable?

I know that undeclared variables won't generate an error in my Unexplicit case, but I want to know if it is usefull to declare my string variables.
Avatar of harsh008_k
harsh008_k

well!
There is use in
Option Explicit
'this will force u to declare the variable before use.
'u could do with out it
'but u can fall prey to ur typo error
'ex- if u say
ii=12
ii=ii+10 u get ii=22
by mistake if u say ii=i+10 (u forget to add one more i)
u get ii=10 and not 22 as u expected.
u will have hard 2 find bugs

so My suggestions is 2 use Option Explicit
U can got o tools-options-Require Variable Declaration
u will auotmaitcally get Option Explicit in all the new forms u create


****Regarding using of Dim****

U gotta do this to specify the scope of variable**

If u declare at the general declaration section,it will apply to all procedures.
if u declare with in a procedure,its scope is limited to the procedure
But u gotta declare Dim/Private.
Else Use Public in standard Module to acces variable in all forms
else
use static in Procedure if want a static variable

I hope this is enough.if u want anything specifice u can gimme a feeback
If u dont declare the variable as string,ti will take as a variant.

dim i
i="cal"
its sub type will be string
but it occupies more space
All,

Please reread my question:

1/ I don't use Option Explicit, know what it means, and don't WANT to use it
2/ My variables have a $ at the end, which makes them already strings by default.

Example

Sub Test()
myString$ = "Calacuccia"
End Sub

Sub Test2()
Dim myString$
myString$ = "Calacuccia"
End Sub

Is the Dim line in Test2 necessary or not?

calacuccia
Hi calacuccia,

Declare a variable is useful as it determine the bytes to used in memory for those variable.

As harsh mentioned also:

Dim string$  'string is String data type Variable

while

Dim string  'string is Variant data type Variable

Hi,

In your Module:

Public myString$

And you can discard the Dim myString$ in Sub Test2()
Dim is absolutly necessay

this is because ,u gotta mention the scope of the variable
u can do
Dim str$ 'string type vaiable 'both are right
dim str  ' variant

not just str$  will give an error
Why would I have to declare it at module level when I only need it in the procedure. The question remains the same

What is the benefit of doing

'---Start of module
Sub Test2()
Dim myString$
myString$ = "Calacuccia"
End Sub
'---End of module

or

'---Start of module
Public myString$
Sub Test2()
myString$ = "Calacuccia"
End Sub
'---End of module

While I could do this as well:


'---Start of module
Sub Test()
myString$ = "Calacuccia"
End Sub
'---End of module
u can discard dim if u have already declared elsewhere(general section)  which has more scope then ur scope only for ur procedure
Uuuummm....

"just str$ will give an error"

I have used it often, always without an error (bear in mind I'm a Office VBA guy).
If u want the same variable in more then one procedure in the same module,then u gotta declare at the beginning.
If u want it in only one procedure then u gotta/u can if u want in procedure itself
Still no one has answered my question. I'll restate it one again :-)

Is it necessary to declare a string variable by using a declaration line (Dim, Public, Static, anything) if the variable is intrinsically declared by the type-declaration character ($)?
Declaring by Dim statement will indicate the compiler to allocate approriate memory for the variable before assingment which is more reliable and faster,then without declaring it,will make the compiler to identify the data type and then allocate the memory and then assign the value.So use of Dim is always better.
Hi calacuccia,

This is Correct:

'Option Explicit

Private Sub Command1_Click()
    String1$ = "123"
    MsgBox VarType(String1)
    'This will return 8 as vbString ( String data type )
End Sub

This is Wrong:

Option Explicit

Private Sub Command1_Click()
    String1$ = "123" '< - Error
    MsgBox VarType(String1)
    'This will return 8 as vbString ( String data type )
End Sub

It will show a error message: Variable Not Defined.

'Regards.
I think from the previous comments that Option Explicit should be used. Any programmer worth his salt uses it. The fact that you do not want to use it is indicative of in-experience. Stay with tried and tested procedures. Bucking the System seldom leads to success in this business.

In answer to your Question NO you do not have dimension the variable if Option Explicit is not used.

Why not just try it instead.
BGilham,

I won't use it in this project, period. I am very experienced in Office VBA, where the 'Option Explicit' is not added by default. I know the benefits and shortcomings of not using this, and will stick to my experience. I don't have a problem to make my project run neither, this question was more out of curiosity.

pritam_dewan has the kind of comment I was looking for. I'll wait a couple of hours before closing this question, though, see it there are other opinions about this memory allocation.
Not using Option Explicit may be your choice, but your are inviting a major disaster to visit your front door.  Option Explicit serves TWO purposes, the first is to REQUIRE that all varaibles be declared (you are free to simply use the Dim MyVar form, which will declare MyVar as a VARIANT).  The SECOND purpose (and to my way of thinking the MOST IMPORTANT) is to insure that all variables ARE DECLARED.   Without Option Explicit, you cxan easily mis-spell a Varaible name and never know it.  Then you get a new variable (set to whatever is the appropriate default value) where you are expectng to be using the original (and correct) value.

Not using Option Explicit makes absolutely no sense to me.  I have been a professional developer for more than 35 years, and a VB/VBA developer exclusively for more than 7 years, and I can think of ABSOLUTLEY NO SET OF CIRCUMSTANCES under which I would voluntarily choose to NOT use Option Explicit.  but that that is just my personal (but absolutely correct) opinion.

That said, using the form Dim str$ (even without Option Explict) will exsure that the variable str is in fact declared as a STRING type .  VARIANT type variables are VERY expensive in terms of both storage and Performance.  Even without Option Explicit, you should ALWAYS declare variables of the CORRECT type, and should not rely on the fact that VB can convert VARIANT types as necessary - it is that conversion that will cause a performance hit.
Please reread my question, Arthur.

I don't disagree with you, Option Explicit should be used ........ but that is not my question. My question is about type-declaration character vs. Dim statement.
and you should read what I stated, starting with "That said..."
Excactly ;-)

Your paragraph "That Said..." talks about Variant data type, but if I use write this:

mString$ = 5

Is mString not automatically declared as a string variable?

That's my question.
ASKER CERTIFIED SOLUTION
Avatar of Arthur_Wood
Arthur_Wood
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi calacuccia,

yes , mString$ will be a string variable.

From MSDN: The dollar sign ($) type-declaration character represents a String in Visual Basic.
M$ says, in  MSDN ;
You don't have to declare a variable before using it. For example, you could write a function where you don't need to declare TempVal before using it:

Function SafeSqr(num)
   TempVal = Abs(num)
   SafeSqr = Sqr(TempVal)
End Function

Visual Basic automatically creates a variable with that name, which you can use as if you had explicitly declared it. While this is convenient, it can lead to subtle errors in your code if you misspell a variable name.

........................

Local variables are a good choice for any kind of temporary calculation. For example, you can create a dozen different procedures containing a variable called intTemp. As long as each intTemp is declared as a local variable, each procedure recognizes only its own version of intTemp. Any one procedure can alter the value in its local intTemp without affecting intTemp variables in other procedures.

When you use a variable with the type declaration characters you are performing the same operation as DIM, just later. VB doesn't care if you DIM or not. It will upon entering the procedure reserve space on the stack for your local variables.

The real difference between DIM and not DIM come when you want to use a value stored in a variable BETWEEN procedures. Variable used without declaring them first are considered local and will be destroyed upon the procedure they were declared in exits. Additionally, because they are local they are not useable in any procedure called from the procedure they were declared in.

So you can do it either way. Just remember w/o DIM no global variables. Every variable is local.
I hope I've read this question correctly!

I don't imagine there's really any technical difference / technical advantage to using intrinsic type declaration characters.

That is (assuming you are non-option explicit), "Dim n as Integer" and "n%=0" will both allocate memory for an integer (if it's the same as C it'll allocate 4 bytes from the stack), and set that integer value to zero. I doubt there are any performance differences between the two techniques - not with modern compiler optimisations.

As far as I know, it's just a question of recommended practice. I'm surprised anyone uses type declaration characters. They're a monolithic dinosaur present in the original BASIC interpreter circa 1965-ish (I think the idea was borrowed from FORTRAN). The only reason VB6 supports them is to try and maintain some vestige of backwards compatibility with legacy code. I'm reliably informed that VB6 also supports ancient features such as line numbering and the DEF<type> statement, eg. DEFINT, DEFSTR!

I have a funny feeling that identifier type declaration characters may be either deprecated or even completely discarded in VB 7 (.NET). I could be wrong about this, though.

Pardon me if I'm talking out of my rectum.

Regards
My suggestion sincerely is ,Stick to basic,after all this I am wondering if are making mountain out of mole hill
I consider this question solved now, but as we are getting a good discussion, I'll keep it open for a while. I'll award the points to Arthur_Wood.

There might drop some points for other contributions as well.... but they are not declared yet.

baldrick,
you did read it correctly ;-)
As for your rectum, I can't judge for that.
>You don't have to declare a variable before using it. For
>example, you could write a function where you don't need
>to declare TempVal before using it:
>
>Function SafeSqr(num)
>  TempVal = Abs(num)
>  SafeSqr = Sqr(TempVal)
>End Function
>
>Visual Basic automatically creates a variable with that
>name, which you can use as if you had explicitly
>declared it. While this is convenient, it can lead to
>subtle errors in your code if you misspell a variable
>name.

In this case, TempVal is a VARIANT (as is 'num' and SafeSqr()), which incurrs a greater cost in terms of resources and overhead than if you had declared them of a certain type.

In some cases, you need to use variants because the specific data type is unknown, or because you're dealing with arrays, etc.

But this has no bearing on the use or nonuse of the Option Explicit statement and the declaring of variables before you use them.


There is no good reason *not* to use both Option Explicit and to declare your variables prior to their use. If you don't use Option Explicit, you still should declare your variables before using them. Option Explicit simply helps you comply with that rule-of-thumb of declaring variables prior to their use.


By using Option Explicit and declaring your variables, you reap the following benefits:

   1) Your code is more self-documenting. You should use meaningful names for all your identifiers (variables, procedures, etc)

   2) It is clear that you are using certain variables *on purpose*, and that it was not an accident. If you had named a variable 'PersonName' and later on in the code referred to 'PName' because you thought that's what you had named it, you will not get the expected results because you're using two different and distinct variables, not one as you expected. Using Option Explicit would identify this problem before it became problematic.

   3) Along the same lines of #2, you could inadvertantly mistype an identifier's name:   'Perosn' instead of 'Person'   And if it is a Function's name that you mistyped, or a property name, then you'd be creating a new variant variable instead of using the existing function/property. Using Option Explicit eliminates this problem.

   4) Using Option Explicit can greatly reduce costly troubleshooting time, because it eliminates the types of errors described above.


Incidently, I do not recommend the use of type-declaration characters, for the following reasons:

   1) Type-declaration characters are obsolete
   2) Not every data type has a type-declaration character
   3) Declaring variables using "As ????" is better self-documenting code, IMHO
   4) Mixing the use of type-declaration characters and "As ????" gives the air of inconsistency when reviewing the source code. (remember not all datatypes have type-declaration characters)
   5) The use of type-declaration characters are not considered to be good programming practice in the industry


Those are my comments on the matter. But to each his/her own.


-Dennis Borg
obviously, Option Explicit should be used in all cases, by not using it you are making a big mistake, what is the point of all these other questions you are asking when it is obvious that you should be using Option Explicit!!!!??!!

please change your question so that it incorporates the need to use Option Explicit  and how this method is better than anything you could wonder about or care for.... special emphasis should be put in the form of expressing your desire to use Option Explicit and how any other means is both futile and/or wasteful or resources, then i will consider posting an answer telling you that you are right, until then you are most definitely wrong!!!!!














hehehehe   jk    funny?  heh :-)
Not sure I understood thread corrctly, but...
What are you speaking about? VB IDE or compiled EXE? Compiled EXE containg ALL variables DECLARED. VB compiler (C2) use Dim statement as well as type chars to calculate memory needed or use Variant type if no Dim neither charcters present. So Dim myStr$, Dim myStr As String, myStr$ = ... are same for compiler (not sure, may be there is some difference in time of compiling (NOT running!). You don't need double declaring:
Dim myString$ ' no need
myString$ = "Calacuccia"

But, concerning type-declaration characters, see Dennis Borg's comment above (1 -5). Rulez! I've nothing to add.

Cheers
Ark,
I'm talking about VB IDE.

Somebody_Else,
<Smiles>. I've changed my complete project to contain an Option Explicit statement, now tell me I am right.

Thanks to all, for your time to read through this, and your comments.

As said above, points go to Arthur_Wood.

Cheers
calacuccia