简体   繁体   中英

Why can't I use my variable inside this if statement?

I'm trying to add 1 to my variable sum but the compiler says

the variable sum is unassigned

inside my if statement. I've tried moving it around but no matter what I do the variable is still unassigned.

static void Main()
{
    int sum;

    if(true)
    {
        sum += 1;
    }

    Console.Write(sum);
    Console.ReadKey();
}

How can change my code to fix this error and stop the compiler complaining?

The variable sum must have an initial value:

int sum = 0; //or any other value

in your code

static void Main()
{
    int sum = 0;

    if(true)
    {
        sum += 1;
    }

    Console.Write(sum);
    Console.ReadKey();
}

Think about, until sum is assigned a value, is has no defined value, it is undefined. What would the result of

undefined + 1

be, the compiler can't know so raises an error and halts compilation.

There's a difference between a variable being declared ("I do declare sum to be a thing of type int ") and it's value being defined (or, rather assigned ).

Make sure a value has been assigned to them before you evaluate:

static void Main()
{
    // sum is declared as an int and an initial value of 0 is assigned to it
    int sum = 0;

    if(true)
    {
        sum += 1;
    }

    Console.Write(sum);
    Console.ReadKey();
}

It is because the sum is initialized inside the for loop and is is based on the previous value of the sum which is not given. There are two ways to solve the problem. Either initialize sum variable with zero ( int sum = 0 ). Or initialize sum before the for loop. I think the second option makes more sense because you might want to have the cumulative result after the for loop ends.

Before using any local variable, it has to be initialized or defined. Since sum is not defined, you are getting this error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM