C ++ / CLI reference not initialized to nullptr on subsequent entries to local block
I thought that in C ++ / CLI declaring a local reference variable without an explicit initial value, I always initialized it to nullptr. I find it doesn't happen in the second and later entry in the local block. Here's a sample code.
void main()
{
for (int i=0; i<6; i++)
{
switch (i)
{
case 2:
Console::WriteLine("i={0} localI and hashTable no longer in scope", i);
break;
default:
{
// Declare local reference variable
Hashtable^ hashTable;
Int32 localI;
Console::WriteLine("i={0} localI={1} {2}",
i, localI,
hashTable == nullptr ? "hashTable=nullptr" : "hashTable NOT SET to nullptr"
);
hashTable = gcnew Hashtable();
localI = i+1;
}
break;
}
}
}
Way out of this:
i=0 localI=0 hashTable=nullptr
i=1 localI=1 hashTable NOT SET to nullptr
i=2 localI and hashTable no longer in scope
i=3 localI=2 hashTable NOT SET to nullptr
i=4 localI=4 hashTable NOT SET to nullptr
i=5 localI=5 hashTable NOT SET to nullptr
If I add explicit initialization
Hashtable^ hashTable = nullptr;
Int32 localI = 99;
Then each loop reinitializes the reference and localI
i=0 localI=99 hashTable=nullptr
i=1 localI=99 hashTable=nullptr
i=2 localI and hashTable no longer in scope
i=3 localI=99 hashTable=nullptr
i=4 localI=99 hashTable=nullptr
i=5 localI=99 hashTable=nullptr
This seems to contradict what I found here on MSDN which says:
"The following code example shows that when descriptors are declared and not explicitly initialized, they are initialized to nullptr by default."
source to share
This is by design, the CLR only initializes local variables when a method is entered. Scope blocks within a method are language detail that disappears after compilation. Other managed languages ββare the same, VB.NET behaves exactly the same. C # does too, but doesn't allow this kind of code due to its specific assignment rule.
This behavior makes it much easier to implement execution. Jitter just generates code to push the frame stack to zero on write.
source to share