Unreachable code detected in the for loop

14.3k Views Asked by At

I'm trying to find out if a number is prime or not. But I've got an error of "unreachable code detected", which I think is effecting the error of "not all code paths return a value". The error seems to occur in the for loop at i++. Can anyone help me please?

static void Main(string[] args)
    {
        Console.WriteLine(isPrime(10));
    }

    public static bool isPrime(int n)
    {
        for (int i = 2; i < n; i++)
        {
            if (n % i == 0)
            {
                return false;
            }
            return true;
        }
    }
3

There are 3 best solutions below

1
On

"Unreachable code detected" means that some code can never be executed. Consider:

int something()
{
  if (true)
    return 1;
  else
    return 2; //Obviously we can never get here
}

"Not all code paths return a value" means that you've defined a method with a return value (like "bool" in your example) and there is some way for the method to execute without returning a value.

Consider:

int something(bool someBool)
{
  if (someBool)
    return 1;
  //if someBool == false, then we're not returning anything.  Error!
}
0
On

Your code has two problems:

  1. You have return true inside the for loop (outside of any conditional). Because return immediately exits the function (returning control to the caller) the i++ statement of the for loop will never get executed (hence your bug). You likely intended for that to be outside the for loop.

  2. Another problem with that being in the loop is that the loop is not guaranteed to execute. If the n passed was 2 or less, you would skip the loop entirely, and there is no return statement in that case. This isn't allowed (since you always need to return a value from a non-void function) so you get a compiler error.

0
On

Below is an example of how to get this return working with a for loop and embedded If condition.

private bool WinOneLevelOne()
{
    //For loop to check all the items in the winOne array.
    for (int i = 0; i < winOne.Length; i++)
    {
        //If statement to verify that all the gameobjects in the array are yellow.
        if (winOne[i].gameObject.GetComponent<MeshRenderer>().material.color != Color.yellow)
        {
            //Keeps the boolean at false if all the gameobjects are not yellow.
            return false;
        }
    }
    return true;