Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of unassigned local variable?

Tags:

c#

Visual Studio keeps saying Use of unassigned variable for iVal and iNumber. Can anyone tell me where I'm going wrong?

This is designed to be a code to ask the user to keep entering integers and adding them up until the user wants to stop. The sum of the integers is then displayed on the console.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AddFive
{
    class Program
    {
        static void Main(string[] args)
        {
           int iNumber;
           int iVal;
           int iTotal = 0;

            while (iVal > 0)
            {
                Console.WriteLine("Enter number " + iNumber);
                iVal = Convert.ToInt32(Console.ReadLine());
                iTotal = iTotal + iVal;
            }

            if (iNumber <= 0)
            {
                Console.WriteLine("Total = " + iTotal);
                iVal = Convert.ToInt32(Console.ReadLine());
                iTotal = iTotal + iVal;
            }

            Console.WriteLine("Total = " + iTotal);
            Console.WriteLine();
            Console.WriteLine("Press any key to close");
            Console.ReadKey();
        }
    }
}
like image 408
user2052241 Avatar asked Nov 30 '22 13:11

user2052241


2 Answers

Assign values to those variables. You need to assign values to local variables before using them

    int iNumber = 0;
    int iVal = 0;

when you wrote while (iVal > 0), the value of iVal has not been set

You can get away with that only with instance/class variable, as they are initialized to default value

public class Program
{
    int i; //this was not implicitly initialized to zero (0)

    public Program()
    {
        int j; //need to initialize this before use

        Console.Write(j);  //this throws "Use of unassigned variable" error
        Console.Write(i);  //this prints 0, the default value
    }
}
like image 159
codingbiz Avatar answered Dec 05 '22 01:12

codingbiz


Visual Studio is correct, you're trying to reference an uninitialized variable.

Try this:

 int iNumber = 0;
 int iVal = 0;

This way, your are initializing the variables to an initial value of 0. The original problem occurs on these lines:

while (iVal > 0) and if (iNumber <= 0)

In which you try to access the variables before giving them a value.

like image 28
Blachshma Avatar answered Dec 05 '22 03:12

Blachshma