samedi 30 octobre 2021

Why does this if statement not intialize or update my variable?

I'm a bit confused about declaring variables and then initializing/assigning those variables in a code block such as an if statement, then using that variable in the rest of my code.

The following example fails to assign the result of num1 + num2 to "result" in the if statement if "result" is declared and not initialized beforehand.

        int num1 = 1;
        int num2 = 2;
        int result; //declared

        if (num1 == 1)
        {
            result = num1 + num2;
        }
        Console.WriteLine(result); //Use of unassigned local variable "result"

However, declaring and initializing "result" beforehand successfully updates the "result" value in the if statement.

        int num1 = 1;
        int num2 = 2;
        int result = 0; //declared and initialized

        if (num1 == 1)
        {
            result = num1 + num2;
        }
        Console.WriteLine(result); //3

Moreover, if I change the condition in the if statement simply to "true" instead of "num1 == 1", then both of the previous examples work perfectly.

Could someone kindly explain this to me?

Aucun commentaire:

Enregistrer un commentaire