1

In the example below, the compiler generates an error "Use of unassigned local variable r", even though I assign the variable in loop before using it. Why does the compiler generate this error?

static void Main(string[] args)
{
    float r;

    for (int i = 0; i < 100; i++)
        r = i; // assigned here

    Console.WriteLine(r); // error: use of unassigned local variable            
}
AGB
  • 2,230
  • 1
  • 14
  • 21
user1899020
  • 13,167
  • 21
  • 79
  • 154

1 Answers1

11

The compiler generates that error whenever it detects an unassigned variable is possible.

Because the body of for loops are not guaranteed to execute—for example, for(int i = 123; i < 0; i++)—the variable is not guaranteed to be assigned, and so the compiler generates the error.

From the documentation:

The C# compiler does not allow the use of uninitialized variables. If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165. For more information, see Fields (C# Programming Guide). Note that this error is generated when the compiler encounters a construct that might result in the use of an unassigned variable, even if your particular code does not. This avoids the necessity of overly-complex rules for definite assignment.

AGB
  • 2,230
  • 1
  • 14
  • 21
  • I understand your answer from other Types but float has a default value (0). same happens with int, which also has a default value of 0 according to https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/default-values – julian bechtold May 13 '22 at 08:58
  • 1
    Default values come into play when you initialize a variable; they aren’t involved in a declaration. This answer has a helpful breakdown of the differences: https://stackoverflow.com/a/32291033/3159635 – AGB Jun 25 '22 at 19:10
  • what I don't understand is, how the default value plays a role, when it only comes into play when I initialize a variable. Lets say, I `int i = 1;` it could never be the default value, except I go for `int i = 0;` what are the default values for then? – julian bechtold Jun 26 '22 at 09:06