Search code examples
c#compiler-errorsreturn

CS0161: not all code paths return a value


In the following C# snippet, I loop through all integers, up till x, and return as soon as a divisor of x is found.

class Program
{   
        static void Main(string[] args)
        {

        }
        static int LowestDivisor(int x)
        {
            if (x < 0)
                x *= -1;
            if (x == 0 || x == 1)
                return -1;
            for (int i = 2; i <= x; i++)
            {
                if (x % i == 0)
                {
                    return i;
                }
            }
        }
    }
}

I don't see what causes the compiler to give the error CS0161: not all code paths return a value. In the case of a prime number, the last iteration of the for loop returns the prime. If not, a divisor would be returned in an earlier iteration. Hence, for all code paths, a value is returned. Am I wrong?


Solution

  • The compiler can't know that on of the ifs will eventually evaluate to true. You need some default return value after the for loop, even if it's never reached in practice:

    static int LowestDivisor(int x)
    {
        if (x < 0)
            x *= -1;
        if (x == 0 || x == 1)
            return -1;
        for (int i = 2; i <= x; i++)
        {
            if (x % i == 0)
            {
                return i;
            }
        }
        // Should never happen...
        return x;
    }