jarombra jarombra - 3 months ago 24
C# Question

Basic C# calculator exercise - "Use of unassigned local variable" error

I'm practicing switch statements with a very basic calculator script, but am confused why my final line which writes out the float variable result is receiving the error: "Use of unassigned local variable". And yes, there are much better ways to make a calculator involving loops, which I want to try next, but for now it's C# baby steps. Below is my code, thanks everyone!

namespace Calculator
{
class Program
{
static void Main(string[] args)
{
// Greeting.

Console.WriteLine ("Welcome to the basic calculator");

// Get first value.

Console.WriteLine ("Enter the first value.");
string firstValueAsText = Console.ReadLine ();
float a = Convert.ToSingle (firstValueAsText);

// Get second value.

Console.WriteLine ("Enter the second value.");
string secondValueAsText = Console.ReadLine ();
float b = Convert.ToSingle (secondValueAsText);

// Prompt operation.

Console.WriteLine ("Enter '+', '-', '*', '/', '^'.");
string operation = Console.ReadLine ();

// Establishing the result and error variables for later.

float result;
string error = "ERROR";

// Define switch operations.

switch (operation)
{
case "+":
result = a + b;
break;
case "-":
result = a - b;
break;
case "*":
result = a * b;
break;
case "/":
result = a / b;
break;
case "^":
result = (float)Math.Pow(a, b);
break;
default:
Console.WriteLine (error);
break;
}

// Print the result.

Console.WriteLine (a + " " + operation + " " + b + " = " + result);
Console.ReadKey ();
}
}
}

Answer

If a user enters an invalid operation it'll go into the default: flow. In that case result will never be assigned.

You can fix this by doing:

float result = 0;

or:

default:
    Console.WriteLine (error);
    result = 0;
    break;