Home > Software engineering >  Why must a variable be assigned before a for loop
Why must a variable be assigned before a for loop

Time:09-17

The following code produces a "Use of unassigned local variable 'foo'" error. It is easy to fix by replacing double foo; with var foo = 0d; but I would like to understand, why the compiler (Visual Studio) complains. In my opinion, there is no way var bar = foo; can be reached without assigning foo in the for loop.

    class Program
    {
        static void Main(string[] args)
        {
            double foo;
            for (var i = 0; i <= 5; i  )
            {
                foo = 1.23;
            }
            var bar = foo;
        }
    }

Many thanks.

CodePudding user response:

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.

Here is more.

CodePudding user response:

Loop parameters are usually evaluated at runtime, so the compiler has no way of knowing the condition of your loop. Because it's obviously possible for a for loop not to run at all (if the condition is initially false), the compiler warns you with an error about the potential use of an unassigned variable.

CodePudding user response:

Because the compiler can't be sure whether foo will be assigned in the loop. Maybe in your case it's possible to infer, but the compiler just doesn't support that. Also it's bad practice in C# to declare variable without initial value.

  • Related