Why does a for loop invoke a warning when using identical code?

I think that following two codes are identical. but upper one has C4715 "not all control paths return a value" problem and other doesn’t.
Why this warning happens?

int func(int n){
    for(int i=0; i<1; i++){
        if(n == 0){
            return 0;
        }
        else {
            return -1;
        }
    }
}
int func(int n){
    if(n == 0){
        return 0;
    }
    else {
        return -1;
    }
}

>Solution :

The compiler is trying to be helpful, and failing. Pretend for a moment that the code inside the loop was just if (n == 0) return 0;. Clearly, when n is not 0, the loop will execute once and then execution will move on to the next statement after the loop. There’s no return statement there, and that’s what the compiler is warning you about. It just isn’t smart enough to see that the code inside the loop always returns.

So, possibly, add a return 0; statement after the loop. That might make the compiler happy. But it also might make the compiler (or some other compiler) give a different warning about "unreachable code", because that new return statement can’t actually be reached. This stuff is hard to analyze, and compilers often get it wrong.

Leave a Reply