CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Oct 2010
    Posts
    2

    What's wrong with this code?

    It won't compile because of a "Use of unassigned local variable 'answer' "
    Any help would be appreciated, and don't flame because I'm still a beginner.
    Code:
            string theOperator;
            private void btnAnswer_Click(object sender, EventArgs e)
            {
                int firstTextBoxNumber = int.Parse(tbFirstNumber.Text);
                int secondTextBoxNumber = int.Parse(tbSecondNumber.Text);
                int answer;
                theOperator = tbOperatorSymbol.Text;
    
                switch (theOperator)
                {
                    case "+":
                            answer = firstTextBoxNumber + secondTextBoxNumber;
                            break;
                    case "-":
                            answer = firstTextBoxNumber - secondTextBoxNumber;
                            break;
                    case "*":
                            answer = firstTextBoxNumber * secondTextBoxNumber;
                            break;
                    case "/":
                            answer = firstTextBoxNumber / secondTextBoxNumber;
                            break;
                    default:    
                            //Insert Code
                            break;
                }
    
                MessageBox.Show(answer.ToString());
            }

  2. #2
    Join Date
    Jan 2002
    Posts
    87

    Re: What's wrong with this code?

    If the "switch" statement goes through "default" the "answer" variable does not get assigned, i.e. MessageBox at the end of the program does not know what to use if your program "switch" goes in "default".

    To fix is you can either assign "answer" when declaring it, i.e.
    Code:
    int answer = 0; // or something else
    or directly in the "switch" statement after "default":
    Code:
    ...
    default:
       answer = 0; // or whatever you wish
       break;

  3. #3
    Join Date
    Oct 2010
    Posts
    2

    Re: What's wrong with this code?

    Thanks man, but I already figured that out after I posted...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured