Solved

Simple Declaration Question

Posted on 2001-08-30
32
498 Views
Last Modified: 2012-06-27
<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
0
Comment
Question by:calacuccia
  • 10
  • 6
  • 5
  • +9
32 Comments
 
LVL 49

Expert Comment

by:Ryan Chong
Comment Utility
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.

0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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.
0
 
LVL 1

Expert Comment

by:harsh008_k
Comment Utility
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
0
 
LVL 1

Expert Comment

by:harsh008_k
Comment Utility
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
0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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
0
 
LVL 49

Expert Comment

by:Ryan Chong
Comment Utility
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

0
 
LVL 49

Expert Comment

by:Ryan Chong
Comment Utility
Hi,

In your Module:

Public myString$

And you can discard the Dim myString$ in Sub Test2()
0
 
LVL 1

Expert Comment

by:harsh008_k
Comment Utility
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
0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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
0
 
LVL 1

Expert Comment

by:harsh008_k
Comment Utility
u can discard dim if u have already declared elsewhere(general section)  which has more scope then ur scope only for ur procedure
0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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).
0
 
LVL 1

Expert Comment

by:harsh008_k
Comment Utility
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
0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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 ($)?
0
 

Expert Comment

by:pritam_dewan
Comment Utility
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.
0
 
LVL 49

Expert Comment

by:Ryan Chong
Comment Utility
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.
0
 
LVL 3

Expert Comment

by:BGillham
Comment Utility
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.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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.
0
 
LVL 44

Expert Comment

by:Arthur_Wood
Comment Utility
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.
0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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.
0
 
LVL 44

Expert Comment

by:Arthur_Wood
Comment Utility
and you should read what I stated, starting with "That said..."
0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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.
0
 
LVL 44

Accepted Solution

by:
Arthur_Wood earned 50 total points
Comment Utility
ok, now i got what you were asking...in that case the variable mString is a String (not you can refere to the varaible, after it is assigned, as either mString$ or mString)

0
 
LVL 49

Expert Comment

by:Ryan Chong
Comment Utility
Hi calacuccia,

yes , mString$ will be a string variable.

From MSDN: The dollar sign ($) type-declaration character represents a String in Visual Basic.
0
 
LVL 3

Expert Comment

by:3rsrichard
Comment Utility
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.

0
 
LVL 3

Expert Comment

by:MCummings111400
Comment Utility
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.
0
 
LVL 3

Expert Comment

by:baldrick
Comment Utility
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
0
 
LVL 1

Expert Comment

by:harsh008_k
Comment Utility
My suggestion sincerely is ,Stick to basic,after all this I am wondering if are making mountain out of mole hill
0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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.
0
 
LVL 8

Expert Comment

by:DennisBorg
Comment Utility
>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
0
 
LVL 3

Expert Comment

by:Somebody_else
Comment Utility
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 :-)
0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
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
0
 
LVL 17

Author Comment

by:calacuccia
Comment Utility
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
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Introduction I needed to skip over some file processing within a For...Next loop in some old production code and wished that VB (classic) had a statement that would drop down to the end of the current iteration, bypassing the statements that were c…
Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now