2

I'm getting the following error:

Use of unassigned local variable.

enter image description here

Code:

int c;
for (int b = 1; b < 5; b++)
{
    c = b * 2;
}
nickb
  • 59,313
  • 13
  • 108
  • 143
  • 2
    Possible duplicate of [Why compile error "Use of unassigned local variable"?](http://stackoverflow.com/questions/9233000/why-compile-error-use-of-unassigned-local-variable) – Sinatr May 23 '16 at 15:09
  • :)) oh. I fogot it when compiled – Hung Nguyen May 23 '16 at 15:23

2 Answers2

4

replace

int c;

with

int c = 0; //or some other initial value

The error appears because the compiler doesn't know if the loop is ever excecuted / a value is assigned to c. So it doesn't allow you to use it Console.WriteLine(c);

int c; // this works because the compiler knows there is a values assigned to c
c = 1;
Console.WriteLine(c);
fubo
  • 44,811
  • 17
  • 103
  • 137
  • +1 Thanks :) How to have : " b * ( each element of sloop)" like : 1*(1+2+3+4) And multiply each element in sloop like : 1*2*3*4 – Hung Nguyen May 23 '16 at 14:44
  • 1
    @HungNguyen - this is a separate question. Please post accordingly and be sure to show what you've tried so far – Bob Kaufman May 23 '16 at 14:49
0

You have to assign a value to variable c before using it. like

int c = 1;
Kahbazi
  • 14,331
  • 3
  • 45
  • 76