Search code examples
c#loopsdeclaration

Variable declaration in loop doesn't get reset to default


Consider following code:

for (int i = 0; i < 10; i++)
{
    bool b;          /* #1 */
    if (i == 0)
    {
        b = true;    /* #2 */
    }
}

I have set breakpoints at #1 and #2.

The first time (i = 0), b is set to false at #1 and set to true at #2.

The second time (i = 1), b is true at #1.

This doesn't make sense to me, because I assumed that when starting in the second loop (i = 1), b should be false at declaration again.

I assumed that b = false at #1 in the second loop.

Anyone care to explain?


Solution

  • Note that if you try

    for (int i = 0; i < 10; i++)
    {
        bool b;          /* #1 */
    
        if (!b)
        {
            i = 100000;
        }
    
        if (i == 0)
        {
            b = true;    /* #2 */
        }
    }
    

    You'll get a compile error, since variables must be initialised before use

    but for your curiosity....

    If you look at the IL you'll note that b is declare as local.

    .maxstack 2
    .locals init (
        [0] int32 i,
        [1] bool b,
        [2] bool CS$4$0000
    )
    

    That means it's allocated stack space at when the method is loaded on to the stack. The space it uses won't change during the methods execution so it won't reset unless you tell it to with something like b = default(typeof(bool));