473,473 Members | 1,776 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Uninitialized variables

Is this expected behavior?

Winform with button and listbox:

Dim i As Integer
For i = 0 To 50
Dim s As String
If i = 1 Then
s = "Only once?"
End If
Me.ListBox1.Items.Add("Test " & s)
Next

If I run this code I find that the value of s remains at
"Only once?" through all the iterations after i=1, although
it is not declared as static.

This is certainly what (might) happen in C with an
uninitialized variable, but I though VB was super-safe and
would automatically initialize variables to a sensible default?

If not, surely the VB compiler should do what the C#
compiler does and check for uninitialized variables?

Tim

Nov 20 '05 #1
23 6495
What version of .NET are you using?

--
HTH,
-- Tom Spink, Über Geek

Please respond to the newsgroup,
so all can benefit

"Maybe it's a game called 'Punish the User'"
"Tim Anderson" <ti*****@hotmail.com> wrote in message
news:e8*************@tk2msftngp13.phx.gbl...
Is this expected behavior?

Winform with button and listbox:

Dim i As Integer
For i = 0 To 50
Dim s As String
If i = 1 Then
s = "Only once?"
End If
Me.ListBox1.Items.Add("Test " & s)
Next

If I run this code I find that the value of s remains at
"Only once?" through all the iterations after i=1, although
it is not declared as static.

This is certainly what (might) happen in C with an
uninitialized variable, but I though VB was super-safe and
would automatically initialize variables to a sensible default?

If not, surely the VB compiler should do what the C#
compiler does and check for uninitialized variables?

Tim

Nov 20 '05 #2
Hello,

"Tim Anderson" <ti*****@hotmail.com> schrieb:
Is this expected behavior?

Winform with button and listbox:

Dim i As Integer
For i = 0 To 50
Dim s As String
If i = 1 Then
s = "Only once?"
End If
Me.ListBox1.Items.Add("Test " & s)
Next

If I run this code I find that the value of s remains at
"Only once?" through all the iterations after i=1, although
it is not declared as static.
That's IMHO the expected behavior:

\\\
Dim i As Integer
For i = 1 To 2
Dim s As String
If i = 1 Then
s = "Only once?"
End If
MsgBox(s)
Next i
///

Will show "Only once?" two times. Notice that s will _not_ be destroyed and
re-allocated in every iteration of the loop.
This is certainly what (might) happen in C with an
uninitialized variable, but I though VB was super-safe and
would automatically initialize variables to a sensible default?


The variable will persist over the iterations of the loop. Let's have a
look at the code below:

\\\
Dim i As Integer
For i = 1 To 2
Dim s As String = ""
If i = 1 Then
s = "Only once?"
End If
MsgBox(s)
Next i
///

The code above is the same as this:

\\\
Dim i As Integer
For i = 1 To 2
Dim s As String
s = ""
If i = 1 Then
s = "Only once?"
End If
MsgBox(s)
Next i
///

In both cases, 's' will be allocated only one time and will not be destroyed
(OK, assigning a new value to a string variable creates a new string, but
that's not what I want to say).

Regards,
Herfried K. Wagner
--
MVP · VB Classic, VB .NET
http://www.mvps.org/dotnet
Nov 20 '05 #3
Tim,

Your string is defined with block scope, where the block is the For/Next
loop. You never leave it, so it doesn't get redefined.

Larry Woods

"Tim Anderson" <ti*****@hotmail.com> wrote in message
news:e8*************@tk2msftngp13.phx.gbl...
Is this expected behavior?

Winform with button and listbox:

Dim i As Integer
For i = 0 To 50
Dim s As String
If i = 1 Then
s = "Only once?"
End If
Me.ListBox1.Items.Add("Test " & s)
Next

If I run this code I find that the value of s remains at
"Only once?" through all the iterations after i=1, although
it is not declared as static.

This is certainly what (might) happen in C with an
uninitialized variable, but I though VB was super-safe and
would automatically initialize variables to a sensible default?

If not, surely the VB compiler should do what the C#
compiler does and check for uninitialized variables?

Tim

Nov 20 '05 #4
Hi Tim,

Also, in VB6 there was no concept of Block scope. You will notice that in
VB6 the variable is not re-initialized. In VB.NET we have what is called
Block Scope. Notice that in VB.NET you cannot use the variable 's' outside
of the For/Next loop. Since the scope of 's' is inside of the For/Next and
*not* the procedure it is initialized each time through the For/Next loop.
This is described in:

http://msdn.microsoft.com/library/de...us/vbcn7/html/
vbconscopelevels.asp

The static variable lifetime is different so it doesn't get re-initialized.
Look up lifetime under visual basic language concepts in help and you will
find this explanation:
More stuff on LifeTime:

http://msdn.microsoft.com/library/de...us/vbcn7/html/
vbconlifetime.asp
Regards,
Peter Huang
Microsoft Online Partner Support
Get Secure! www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

--------------------
From: "Tim Anderson" <ti*****@hotmail.com>
References: <e8*************@tk2msftngp13.phx.gbl> <OA**************@TK2MSFTNGP12.phx.gbl>Subject: Re: Uninitialized variables
Date: Tue, 2 Sep 2003 11:15:36 +0100
Lines: 25
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
Message-ID: <uZ**************@tk2msftngp13.phx.gbl>
Newsgroups: microsoft.public.dotnet.languages.vb
NNTP-Posting-Host: pc4-stap2-3-cust205.nott.cable.ntl.com 81.103.228.205
Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!tk2msftn gp13.phx.gbl
Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.languages.vb:133461
X-Tomcat-NG: microsoft.public.dotnet.languages.vb

"Larry Woods" <la***@lwoods.com> wrote in message news:OA**************@TK2MSFTNGP12.phx.gbl...
Tim,

Your string is defined with block scope, where the block is the For/Next
loop. You never leave it, so it doesn't get redefined.


Thanks (and to others) for the comments. I notice VB6 is the same.

I still find the logic of this somewhat puzzling. The Dim keyword declares

andallocates storage space for variables. In this situation though, although theDim statement is executed on each iteration of the loop, it is only effectiveonce. However, if I type:

Dim s As String = String.Empty

then the empty string is assigned on each iteration of the loop. However,
if I type:

Static s as String = String.Empty

the assignment only happens once (which is what I would expect).

Tim


Nov 20 '05 #5
"Peter Huang [MSFT]" <v-******@online.microsoft.com> wrote in message news:2%****************@cpmsftngxa06.phx.gbl...
Since the scope of 's' is inside of the For/Next and
*not* the procedure it is initialized each time through the For/Next loop.
This is described in:


But it is *not* initialized each time, as your referenced tech note makes clear:

"Even if the scope of an element is limited to a block, its lifetime is still that
of the entire procedure. If you enter the block more than once during the
procedure, a block variable retains its previous value."

I don't see the logic of this, particularly since if you want this behavior you
can have it via the static declaration (I realise that static is different in that
its value will persist if the procedure is re-entered, but you could reset the
value at the beginning of the procedure).

However I understand how it works now so hopefully it won't catch me
out (I'm a believer in initializing all variables anyway).

Tim
Nov 20 '05 #6
Hi Tim,

If you change the code
Static s as String = String.Empty
to
Static s as String
s = String.Empty

Then it will be initialized every time you enter the for-next loop. I think
it is by design.

Regards,
Peter Huang
Microsoft Online Partner Support
Get Secure! www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

--------------------
From: "Tim Anderson" <ti*****@hotmail.com>
References: <e8*************@tk2msftngp13.phx.gbl> <OA**************@TK2MSFTNGP12.phx.gbl>
<uZ**************@tk2msftngp13.phx.gbl>
<2#**************@cpmsftngxa06.phx.gbl>Subject: Re: Uninitialized variables
Date: Wed, 3 Sep 2003 07:30:17 +0100
Lines: 23
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
Message-ID: <OW**************@tk2msftngp13.phx.gbl>
Newsgroups: microsoft.public.dotnet.languages.vb
NNTP-Posting-Host: pc4-stap2-3-cust205.nott.cable.ntl.com 81.103.228.205
Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!tk2msftn gp13.phx.gbl
Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.languages.vb:133699
X-Tomcat-NG: microsoft.public.dotnet.languages.vb

"Peter Huang [MSFT]" <v-******@online.microsoft.com> wrote in message news:2%****************@cpmsftngxa06.phx.gbl...
Since the scope of 's' is inside of the For/Next and
*not* the procedure it is initialized each time through the For/Next loop. This is described in:
But it is *not* initialized each time, as your referenced tech note makes

clear:
"Even if the scope of an element is limited to a block, its lifetime is still thatof the entire procedure. If you enter the block more than once during the
procedure, a block variable retains its previous value."

I don't see the logic of this, particularly since if you want this behavior youcan have it via the static declaration (I realise that static is different in thatits value will persist if the procedure is re-entered, but you could reset thevalue at the beginning of the procedure).

However I understand how it works now so hopefully it won't catch me
out (I'm a believer in initializing all variables anyway).

Tim


Nov 20 '05 #7
Peter,

I don't have any problem getting the code to do what I want,
now that I know what VB does.

I just doubt the logic of it, that's all :-)

Given that VB auto-initializes strings to Nothing, one would think
that:

Dim s as String
and
Dim s as String = Nothing

would be equivalent. But they are not!

Thanks,

Tim

"Peter Huang [MSFT]" <v-******@online.microsoft.com> wrote in message news:CA**************@cpmsftngxa06.phx.gbl...
Hi Tim,

If you change the code
Static s as String = String.Empty
to
Static s as String
s = String.Empty

Then it will be initialized every time you enter the for-next loop. I think
it is by design.

Nov 20 '05 #8
Cor
Tim,
I am following this thread from the start.(I even have it in a
testsituation) :-)
If string=nothing means in VB.net string exist but have no value
If string Is nothing means in VB.net if string does not exist.
I would find it very unregular if that logic was not followed in your
examles.
Cor
Nov 20 '05 #9
"Cor" <no*@non.com> wrote in message news:3f***********************@reader20.wxs.nl...
Tim,
I am following this thread from the start.(I even have it in a
testsituation) :-)
If string=nothing means in VB.net string exist but have no value
If string Is nothing means in VB.net if string does not exist.
I would find it very unregular if that logic was not followed in your
examles.


Not sure if I fully understand your comment. Consider this code:

Dim s as String = Nothing
Console.WriteLine(s = String.Empty)
Console.WriteLine(isNothing(s))
Console.WriteLine(isNothing(String.Empty))

This outputs:

True
True
False

Is that what you expect? It strikes me as odd.

Tim
Nov 20 '05 #10
Cor
Tim,
I find it mean from you to mean that what I try to say is mean.
In VB.net we have the Microsoft.Visual Basic commando's and the System.Net
commando's.
That they maybe are look alike doesn't mean they are the same.
Nobody in this thread has spoken about the isNothing function.
But I stop argue with you because it isNothing
I was stupid that I did it not let it be for me Is Nothing.
Succes with others.
Cor
Nov 20 '05 #11
"Tim Anderson" <ti*****@hotmail.com> schrieb
"Cor" <no*@non.com> wrote in message
news:3f***********************@reader20.wxs.nl...
Tim,
I am following this thread from the start.(I even have it in a
testsituation) :-)
If string=nothing means in VB.net string exist but have no value
If string Is nothing means in VB.net if string does not exist.
I would find it very unregular if that logic was not followed in
your examles.


Not sure if I fully understand your comment. Consider this code:

Dim s as String = Nothing
Console.WriteLine(s = String.Empty)
Console.WriteLine(isNothing(s))
Console.WriteLine(isNothing(String.Empty))

This outputs:

True
True
False

Is that what you expect? It strikes me as odd.


- String is a reference type
- String.Empty is a zero-length String.
- When comparing Strings using "=", Nothing is converted to a zero-length
string before comparison (see docs for "=" comparison operator). That's why
the first line returns "True".
--
Armin

Nov 20 '05 #12
"Armin Zingler" <az*******@freenet.de> wrote in message news:ek**************@TK2MSFTNGP11.phx.gbl...
- When comparing Strings using "=", Nothing is converted to a zero-length
string before comparison (see docs for "=" comparison operator). That's why
the first line returns "True".


Well yes, so it seems. I'm not sure though why VB does this.

Tim
Nov 20 '05 #13
"Cor" <no*@non.com> schrieb:
If string=nothing means in VB.net string exist but have no value
It has the value "" ("empty" string, string of length 0).
If string Is nothing means in VB.net if string does not exist.
I would find it very unregular if that logic was not followed
in your examles.


???

--
Herfried K. Wagner
MVP · VB Classic, VB.NET
http://www.mvps.org/dotnet
Nov 20 '05 #14
"Tim Anderson" <ti*****@hotmail.com> schrieb
"Armin Zingler" <az*******@freenet.de> wrote in message
news:ek**************@TK2MSFTNGP11.phx.gbl...
- When comparing Strings using "=", Nothing is converted to a
zero-length string before comparison (see docs for "=" comparison
operator). That's why the first line returns "True".


Well yes, so it seems. I'm not sure though why VB does this.


Because the docs say that it has to work this way.

;-))
--
Armin

Nov 20 '05 #15
Cor
Herfried,
Normaly I just see to this discussions to have fun, I have them seen so
often and they are as the water in the Donau.
If string Is nothing means in VB.net string does not exist.
I would find it very unregular if that logic was not followed
in your examples.


The discussion was about the declaration from strings and what was the logic
behind some things,
But it was moving up and everytime there was a new argument.
When I came in it was about that it was not logic that
string = nothing was equal to string = ""
But in VB is | If String = nothing | something else than | If String Is
nothing|.
Therefore it is logical to keep that logic constant in the language.
What it in another language means is not relevant.

And then came again a new item "IsNothing" which has of course nothing to do
with it.
Or as much as Mid, Len, etc. (just as example not completly)
So I stopped arguing with my standard examples about natural languages.
A word has different meanings, but it has to be posible to evaluate that.
It looks if Tim thinks that a language is a table of mathimatical
instructions.
You know how we think about that.

Cor
ps.
You know of course that mean has minimal 3 different meanings in English.
Nov 20 '05 #16
Does what?

This seems logical. = is a comparison operator, 'Is' is an object reference
comparison.

Reference Types pass themselves around as pointers, so if two pointers are
the same, hurrah! same object reference.

'Is' is used for comparing these pointers.
= is used for comparing values.

So, in the case of =, Nothing is a zero-length string, and in the case of
'Is', Nothing is a null reference pointer.

--
HTH,
-- Tom Spink, Über Geek

Please respond to the newsgroup,
so all can benefit

"Maybe it's a game called 'Punish the User'"
"Tim Anderson" <ti*****@hotmail.com> wrote in message
news:#B*************@TK2MSFTNGP11.phx.gbl...
"Armin Zingler" <az*******@freenet.de> wrote in message news:ek**************@TK2MSFTNGP11.phx.gbl...
- When comparing Strings using "=", Nothing is converted to a zero-length string before comparison (see docs for "=" comparison operator). That's why the first line returns "True".


Well yes, so it seems. I'm not sure though why VB does this.

Tim

Nov 20 '05 #17
"Tom Spink" <th**********@ntlworld.com> wrote in message news:%2****************@TK2MSFTNGP10.phx.gbl...
Does what? So, in the case of =, Nothing is a zero-length string,


IMO Nothing is never a zero-length string.

Tim


Nov 20 '05 #18
"Cor" <no*@non.com> wrote in message news:3f***********************@reader20.wxs.nl...
It looks if Tim thinks that a language is a table of mathimatical
instructions.
Not something I recall saying.
Cor
ps.
You know of course that mean has minimal 3 different meanings in English.


3 words in common usage from different roots. But many different meanings.

Tim
Nov 20 '05 #19
Cor
Tim,
That is the basic why you and me cann't discuss about this.
We have basically different idea's about a language.
It has no sence to talk about a detail when you disagree about the basics.
From your point of view you are right.
From my point of view I am right.
So it is not something personaly, but this discussion between you and me
leads to = nothing.
Cor
Nov 20 '05 #20
"Tim Anderson" <ti*****@hotmail.com> schrieb
"Tom Spink" <th**********@ntlworld.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...
Does what?

So, in the case of =, Nothing is a zero-length string,


IMO Nothing is never a zero-length string.


Tom meant that "in the case of =", Nothing is handled as a zero-length
string, and that is correct. That's what the docs to the "=" comparison
operator say and how it actually works.

IMO, Nothing should never be used with value types at all (as I've already
written several times...), i.e. the compiler should not even allow the usage
with value types, like C# does. Nothing should really mean Nothing, no
object, no thing, not anything... How can I set an Integer variable to
Nothing? Does the variable disappear?? Zero *is* a value, not nothing.
--
Armin

Nov 20 '05 #21
"Cor" <no*@non.com> wrote in message news:3f***********************@reader20.wxs.nl...
Tim,
That is the basic why you and me cann't discuss about this.
We have basically different idea's about a language.


Fair enough, but I'd be interested in a link to something that
summarises your ideas about a language so I can make sure
I disagree with it :-)

Tim
Nov 20 '05 #22

"Armin Zingler" <az*******@freenet.de> wrote in message news:eS*************@TK2MSFTNGP11.phx.gbl...
Tom meant that "in the case of =", Nothing is handled as a zero-length
string, and that is correct. That's what the docs to the "=" comparison
operator say and how it actually works.
Yes, I wasn't disagreeing with Tom's explanation (apologies if it was
taken that way), merely giving my opinion.
IMO, Nothing should never be used with value types at all (as I've already
written several times...), i.e. the compiler should not even allow the usage
with value types, like C# does. Nothing should really mean Nothing, no
object, no thing, not anything... How can I set an Integer variable to
Nothing? Does the variable disappear?? Zero *is* a value, not nothing.


Makes sense to me.

Tim
Nov 20 '05 #23
Cor
Tim
That I will do,
In my opinion is a language to express you. (I always talk about natural
languages)
That can be just talking but too giving commands.
You are able to do that in a language in different ways with different
words.
That is because of your emotions, the situations etc. etc.
The first program languages, I am very long in this business, so I have seen
a lot, where totally bound to the computer or totally mathematical.
They disappeared.
I did VB always find a terrible program language, (Interpreter language with
row numbers and goto's)
VB net has the strange thing that is like the English language a mixture of
2 cultures.
I do not know if you are from Europe, but when you are talking with someone
from Germany in English, they use often other English words than people from
France.
That is possible in VB.net too, and in my opinion that is a benefit I never
saw before in a program language.
Cor

Nov 20 '05 #24

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
by: steve | last post by:
i've setup a include page that's responsible for building the basic layout of my web pages (header, menus, etc.). each page includes this "sysheader.php". the first page i've built with this...
13
by: rswanster | last post by:
When I compile and run the following: #include <iostream> int main() { bool f; std::cout << f << std::endl; f = not(f); std::cout << f << std::endl; }
12
by: jyu.james | last post by:
I'm trying to detect reads of uninitialized global variables (that are declared in one file, and used in another as an extern). I know that ANSI C initializes all global variables to 0, however,...
3
by: julien | last post by:
Hello, Is it possible if a boolean was initialized or not? For other types of variable, I usually check if it is null. But this not possible for a boolean. Thank you Julien
21
by: sanjaymeher | last post by:
Hi, Right now addDynamicMemory(char **ptr, int size) method can able to handle if input ptr is intitialized to NULL or something. But how to improve this method to handle uninitialized pointed...
148
by: onkar | last post by:
Given the following code & variable i . int main(int argc,char **argv){ int i; printf("%d\n",i); return 0; } here i is allocated from bss or stack ?
18
by: Spoon | last post by:
Hello everyone, I suppose using uninitialized automatic integer variables leads to undefined behavior? i.e. int foo(void) { int bar; /* bar may be 0, or it may be non-0 */
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.