views:

70

answers:

3

I just made an interesting mistake in my code:

Dim endColumn As Integer = startColumn + endColumn - 1

The code was actually supposed to be:

Dim endColumn As Integer = startColumn + numColumns - 1

The interesting thing is, I would think that this code should be recursive and loop indefinitely, as the initialization of endColumn sort of calls itself. However, it seems that the code just treats the uninitialized variable as a 0 and so I get startColumn + 0 - 1. What is happening here behind the scenes? When does a variable get assigned a default value?

+6  A: 

The variable isn't uninitialized.

Execution Step 1: Dim endColumn As Integer The default value of an Integer is 0 so endColumn = 0 at this point.

Execution Step 2: startColumn + endColumn - 1 Since endColumn = 0 from step 1, this is the value that is used.

rchern
I don't know why, but this reminds me of Magic: The Gathering.
M.A. Hanin
+5  A: 

The spec says, that:

All variables are initialized to the default value of their type before any variable initializers are executed.

tanascius
A: 

There is no recursion at all here. Reading variables never causes recursion. At worst, I could see the compiler throwing an error in trying to use a variable in its initialization clause, but apparently it does not or you would not have been able to compile in the first case.

Gideon Engelberth