It must be simple, but i can’t seem to find the explanation. Why does the following generates these errors:
- Unreachable code detected (on result++)
-
WindowsFormsApplication1.Form1.GetResult(int, int): not all code paths return a value
private int GetResult(int start, int end) { for (int result = start; result < end; result++) { return result; } }
Anyone who could please help me out? Thnx in advance 🙂
EDIT:
First of all, thanks for the many (fast) replys. Stupid of mine…but i didn’t see it.
And sorry, i needed to be a little more precise of what it is i wanted to accieve..
I need a method that adds 1 to a value (result) starting from the given start value (int start) untill it reaches another value (int end).
So it might also add directly to start integer if I’m not mistaking. And return that value?
What a clever compiler!
… is equivalent to:
If start >= end as we go into this code, the content of the while loop will never run. In that case, the program flow won’t hit a
returnstatement: Not all code paths return a value.If start < end as we enter the function, the program flow will go into the loop, hit the
returnstatement, and the method will return. It can’t hit theresult++statement. Unreachable code detected.In response to your edit:
… does what you describe. However it’s a wasteful way to get that result. If start=0 and end=1000000, the program will loop a million times.
You’d get exactly same result more efficiently with:
Or even:
(Although it’s still not clear what you want the result to be if
start > end)