I am facing a problem related to the scope of the variables used .
code:
int row_no, upflag, downflag;
for (int i = count; i > 0; i--)
{
asd = ds1.Tables[out_table].Rows[i][59].ToString();
int com1 = string.Compare(asd, "Upstream");
int com2 = string.Compare(asd, "Downstream");
if (com1 == 0 || com2 == 0)
{
row_no = i;
if (com1 == 0)
upflag = 1;
else
downflag = 1;
break;
}
}
if (upflag == 1)//
{
string val1 = ds1.Tables[out_table].Rows[count][59].ToString();
string val2 = ds1.Tables[out_table].Rows[(count - 1)][59].ToString();
}
in this code, in the last if(upflag == 1) condition, my VS2010 shows a red line below the upflag and said
use of unassigned local variable ‘upflag’.
why is it so? It was perfectly ok in c++ , but here under multiple nested loops/condition, the value assigned to the variable inside the brackets, does not reflect back outside them, even when the variable is declared before the loop.
Please help
Consider what happens if
count == 0. The body of theforloop will not be executed, and no value will be assigned toupflag. That’s why the compiler said “use of unassigned local variable” – it means it is possible that the variable was not assigned.No, it wasn’t. The compiler might not have complained about it, but it was still undefined behaviour.