English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Why do I get compiler error "Use of an assigned variable 'y'/'x'" when I try to compile this?

private void button1_Click(object sender, EventArgs e)
{
int x, y;
if (checkBox1.Checked)
x = 1;
if (checkBox2.Checked)
y = 2;
if (x+y > 3)
Text = "3";
if (x+y <= 2)
Text = "2";
else
Text = "1";
}

2007-06-05 11:32:57 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

4 answers

x and y are assigned in an if statement.

assign them 0 at the top.

2007-06-05 11:49:05 · answer #1 · answered by Rob 3 · 0 0

Because x and y are only assigned inside a IF statement, there are some "path of execution" where x or y is unassigned (each time checkbox1 or checkbox2 is not checked, x or y is unassigned), so the last 2 if can't be evaluated properly by the compiler (in some langages, anything done with an unassigned variable may lead to *anything*, i.e. it can do something totally unexecpected if it accepts to do anything at all. See for a nice interresting read the "c faq" where some rather simple statements may lead to UNDEFINED behavior, with no garantee to do anything "sane": http://c-faq.com/expr/evalorder4.html (the whole faq is a must read for any C programmer, and in fact any programmer! Think that your nice other langage may use some decisions that sometimes avoid, and sometimes run into, those weird problems) c faq: http://c-faq.com/

2007-06-05 12:39:14 · answer #2 · answered by Anonymous · 0 0

The Unassigned error happens when you assign data to variables only within sections of code which are conditionally branched. Such as within an IF statement...
If all of your IF statments are FALSE then the variable would not be assigned a variable. If you attempt to use the variable later on in something like a limit of a FOR/NEXT the uninitialized variable could cause an error or unintended result.

To avoid this you can do one of two things

1.) initialize the variable to a known value x=0
2.) use IF statements with an ELSE so as to always resolve

IF checkbox.checked then
x=1
ELSE
x=0
end if

2007-06-05 13:56:36 · answer #3 · answered by MarkG 7 · 0 0

The variable "Text" is not declared or qualified.

2007-06-05 11:40:00 · answer #4 · answered by Niklaus Pfirsig 6 · 0 0

fedest.com, questions and answers