Using a nonasigned variable - for loop

I have a question regarding assigning a value to a variable inside a loop for. I understand that the compiler gives this error message when there is a chance that the variable can be read if it is not already assigned, as indicated by Microsoft.

Note that this error occurs when the compiler detects a construct that may lead to the use of an unassigned variable, even if your specific code does not work.

My code is as follows:

static void Main(string[] args)
{
    int i;

    for (int j = 0; j <= 5; j++)
    {
        i = j;
    }

    Console.WriteLine(i.ToString());

    Console.ReadLine();
}

I assume that although it iwill be assigned in this particular scenario , the compiler does not check the actual state inside the statement for, which means that it will refer to

for (int j = 0; j <= -1; j++)

same?

+4
2

, , :

int i;

for (int j = 0; j <= GetUpperLimit(); j++)
{
    i = j;
}

GetUpperLimit 5, -3, i . , . int i = 0 .

const , for . LINQPad:

int i;

for (int j = 0; j <= -1; j++)
{
    i = j;
}

IL:

IL_0001:  ldc.i4.0    
IL_0002:  stloc.1     // j
IL_0003:  br.s        IL_000D
IL_0005:  nop         
IL_0006:  ldloc.1     // j
IL_0007:  stloc.0     // i
IL_0008:  nop         
IL_0009:  ldloc.1     // j
IL_000A:  ldc.i4.1    
IL_000B:  add         
IL_000C:  stloc.1     // j
IL_000D:  ldloc.1     // j
IL_000E:  ldc.i4.m1   
IL_000F:  cgt         
IL_0011:  ldc.i4.0    
IL_0012:  ceq         
IL_0014:  stloc.2     // CS$4$0000
IL_0015:  ldloc.2     // CS$4$0000
IL_0016:  brtrue.s    IL_0005

:

int i;

for (int j = 0; false; j++)
{
    i = j;
}

IL:

IL_0001:  ldc.i4.0    
IL_0002:  stloc.1     // j
IL_0003:  br.s        IL_0005
IL_0005:  ldc.i4.0    
IL_0006:  stloc.2     // CS$4$0000

, if(false) { ... } , bool b = false; if(b) { ... }. .

+4

i for, , , - , , .

.

int i = 0;

, for, .

,

5.3

, , , , , .

, . - , i - .

+13

Source: https://habr.com/ru/post/1524352/


All Articles