-4

I am getting an error can you help me

Visual Studio says there is a problem with the h in the print part:

Error CS0165: Use of unassigned local variable 'h' (CS0165)

static void Main()
{
    int[ , ] m = new int [8,8];
    int i ;
    int h ;
    Random rnd = new Random();
    for( i = 0 ; i< 8 ; i++)
    {
        for( h = 0 ; h< 8 ; h++)
        {
            m[i,h] = rnd.Next(10);
        }
    }
    Console.WriteLine(m[i,h]);
      
}
David
  • 208,112
  • 36
  • 198
  • 279
umut
  • 1
  • 3
    And what is the exact error message? The error is trying to tell you what the problem is, it's best to read and examine it. – David Jun 06 '22 at 18:43
  • I've been working on c# for a month, I'm not good yet on c#, I looked but I don't understand – umut Jun 06 '22 at 18:46
  • Is Visual Studio really telling you "There is a problem with the h in the print part"? Or is there a specific error message? – David Jun 06 '22 at 18:47
  • Error CS0165: Use of unassigned local variable 'h' (CS0165) – umut Jun 06 '22 at 18:49
  • 1
    The compiler doesn't 'know' that the inner loop is supposed to assign a value to h so it doesn't assume it. Why (on earth) don't you initialize your variables??? Always the recommended practice. (Unless you want to test the compiler;-) – TaW Jun 06 '22 at 18:52

1 Answers1

1

Your variables have no assigned values:

int i ;
int h ;

Now, the compiler knows that i will be assigned a value here:

for( i = 0 ; i< 8 ; i++)

Without looking too deep under the hood, basically the i = 0 part is guaranteed to happen whether the loop body executes or not. Then we know that h will also be assigned a value here:

for( h = 0 ; h< 8 ; h++)

Because we know that the outer loop will execute at least once, because we know 0 is less than 8. But the compiler isn't as aware of this. The compiler follows a simpler set of rules for the guarantees that it makes. And those rules do not include executing the program's logic to see if something will or won't happen.

So the bottom line is that, while the compiler can guarantee that i will be assigned a value, it can not guarantee that h will. Hence the error.

The simple solution is just to assign values to your variables:

int i = 0;
int h = 0;
David
  • 208,112
  • 36
  • 198
  • 279
  • actually I tried this but this time i get another error too... System.IndexOutOfRangeException has been thrown – umut Jun 06 '22 at 19:01
  • 1
    @umut: Google is your friend: [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/q/20940979/328193) Now is also a great time for you to start using a debugger to observe the exact runtime values of your variables. You will probably find that on the last line of your program, `i` and `h` have the value `8`, which is invalid for that array. – David Jun 06 '22 at 19:20