Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading