60

I'm trying to write code that returns whether or not a given integer is divisible evenly by 1 to 20,
but I keep receiving the following error:

error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value

Here is my code:

public static bool isTwenty(int num)
{
    for(int j = 1; j <= 20; j++)
    {
        if(num % j != 0)
        {
            return false;
        }
        else if(num % j == 0 && num == 20)
        {
            return true;
        }
    }
}
user2864740
  • 60,010
  • 15
  • 145
  • 220
user115185
  • 735
  • 1
  • 6
  • 7
  • 7
    Your code doesn't make sense but the error message is quite clear. You need to return a value even if both your if conditions are false for 20 iterations. – ChaosPandion Jan 17 '14 at 20:52
  • 10
    You're thinking like a human, not a compiler. The compiler doesn't know what you are thinking, or how the logic is supposed to flow (past optimization). What happens if a value doesnt match either 'if'? – GrandmasterB Jan 17 '14 at 21:08

9 Answers9

114

You're missing a return statement.

When the compiler looks at your code, it's sees a third path (the else you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value.

For my suggested fix, I put a return after your loop ends. The other obvious spot - adding an else that had a return value to the if-else-if - would break the for loop.

public static bool isTwenty(int num)
{
    for(int j = 1; j <= 20; j++)
    {
        if(num % j != 0)
        {
            return false;
        }
        else if(num % j == 0 && num == 20)
        {
            return true;
        }
    }
    return false;  //This is your missing statement
}
  • 1
    This returns the wrong result for `isTwenty(44696171520)`. It should return `true` becase it can be evenly divided by all numbers 1 to 20, but it returns `false`. In fact, it always return `false`, because it can never get into the condition where it would return `true`. – Guffa Jan 17 '14 at 22:07
  • 1
    @Guffa - I think since this question appears to be homework that GlenH7 was doing the bare minimum to get the code to compile without fixing the logic error(s). – James Snell Jan 17 '14 at 23:29
  • 1
    Another option that would reveal the logic error and help this student learn would be to throw an exception instead of returning a potentially wrong value. – James Snell Jan 17 '14 at 23:32
  • 4
    @Guffa - I will somewhat sheepishly admit I didn't try to decipher the rest of the function and focused solely on the error mentioned by the OP. I was equally stumped by the OP's logic expressions but I chose to ignore that in favor of answering the question that was asked. –  Jan 18 '14 at 02:37
10

The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.

Instead of returning in the last iteration, just return true after the loop:

public static bool isTwenty(int num) {
  for(int j = 1; j <= 20; j++) {
    if(num % j != 0) {
      return false;
    }
  }
  return true;
}

Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
8

I also experienced this problem and found the easy solution to be

public string ReturnValues()
{
    string _var = ""; // Setting an innitial value

    if (.....)  // Looking at conditions
    {
        _var = "true"; // Re-assign the value of _var
    }

    return _var; // Return the value of var
}

This also works with other return types and gives the least amount of problems

The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.

Alan Moore
  • 6,525
  • 6
  • 55
  • 68
Evert
  • 81
  • 1
  • 2
7

I like to beat dead horses, but I just wanted to make an additional point:

First of all, the problem is that not all conditions of your control structure have been addressed. Essentially, you're saying if a, then this, else if b, then this. End. But what if neither? There's no way to exit (i.e. not every 'path' returns a value).

My additional point is that this is an example of why you should aim for a single exit if possible. In this example you would do something like this:

bool result = false;
if(conditionA)
{
   DoThings();
   result = true;
}
else if(conditionB)
{
   result = false;
}
else if(conditionC)
{
   DoThings();
   result = true;
}

return result;

So here, you will always have a return statement and the method always exits in one place. A couple things to consider though... you need to make sure that your exit value is valid on every path or at least acceptable. For example, this decision structure only accounts for three possibilities but the single exit can also act as your final else statement. Or does it? You need to make sure that the final return value is valid on all paths. This is a much better way to approach it versus having 50 million exit points.

Sinaesthetic
  • 11,426
  • 28
  • 107
  • 176
3

Or simply do this stuff:

public static bool isTwenty(int num)
{
   for(int j = 1; j <= 20; j++)
   {
      if(num % j != 0)
      {
          return false;
      }
      else if(num % j == 0 && num == 20)
      {
          return true;
      }
      else
      {
          return false; 
      }
   }
}
ForceVII
  • 355
  • 2
  • 16
DareDevil
  • 5,249
  • 6
  • 50
  • 88
  • 1
    This "breaks" the (extremely questionable) logic of the OP's code in that this will always return on the first iteration of the loop. – El Ronnoco Jun 12 '19 at 09:19
1

Have a look at this one. It is the Ternary operator in C#.

bool BooleanValue = (num % 3 != 0) ? true : false;

This is just to show the principle; you can return True or False (or even integer or string) depending on the outcome of something on the left side of the question mark. Nice operator, this.

Three alternatives together:

      public bool test1()
        {
            int num = 21;
            bool BooleanValue = (num % 3 != 0) ? true : false;
            return BooleanValue;
        }

        public bool test2()
        {
            int num = 20;
            bool test = (num % 3 != 0);
            return test;
        }

Even Shorter:

public bool test3()
{
    int num = 20;
    return (bool)(num % 3 != 0);
}
netfed
  • 602
  • 8
  • 18
1
class Program
{
    double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
    double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
    double[] result;


    public double[] CheckSorting()
    {
        for(int i = 1; i < a.Length; i++)
        {
            if (a[i] < a[i - 1])
                result = b;
            else
                result = a;
        }
        return result;
    }

    static void Main(string[] args)
    {
        Program checkSorting = new Program();
        checkSorting.CheckSorting();
        Console.ReadLine();
    }
}

This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true

1

This usually happens to me if I misplace a return statement, for example: enter image description here

Adding a return statement, or in my case, moving it to correct scope will do the trick: enter image description here

Mirza Sisic
  • 2,401
  • 4
  • 24
  • 38
  • 6
    It's always better to use literal code rather than images - if vision-impaired users are using the site, they can't use TTS to read this answer, but they can if you copy in code as text. – Lou Dec 06 '20 at 13:03
0

Not all code paths return a value.

Solution: To solve the error, make sure to return a value from all code paths in the function or set noImplicitReturns to false in your tsconfig.json file.

setzamora
  • 3,560
  • 6
  • 34
  • 48
Jeeva M
  • 1
  • 2