开发者

"Unreachable code detected"

static int Simple() {
    for (int v = 211; v < 661; v++) {
            return v;
   开发者_如何学Python }
}

The 'v' in v++ is underlined and my debugger says unreachable code detected.


Because it will never reach that portion of the code. It will return on first iteration of the for loop. Remember, this is the order of execution of a for loop in C#:

for (init; condition; increment) {
    body;
}
  1. init
  2. condition
  3. body (if condition is true)
  4. increment


The return statement is going to exit the loop immediately, and the v++ won't get a chance to execute.


The compiler will turn your loop into something like:

int v = 211;

loop:
if (v < 661)
{
    return v;
} else {
    v++;
    goto loop;
}


It will never get to do the increment because you are returning the value of v after the first step through the for loop.


you are defining a for loop which iterates over 450 values, but you are returning in the first iteration of the loop (which leaves the function body and therefore stops the execution of the for loop!). Over the other 449 values won't be iterated, so that code is unreachable.


Because v is incremented after the execution of the loop's body. But that tells "hey, don't loop again, go away!", so v will never be incremented.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜