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;
}
}
CodePudding user response:
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.
CodePudding user response:
Because warnings don't promise to only flag incorrect code. Nor do they promise to flag all incorrect code. It's not possible to be completely accurate.
It seems like the part of the compiler that issues C4715 assumes that a for loop with an end condition ends in some cases, and doesn't try to calculate if it will always return early.
CodePudding user response:
My first thought is that the loop cannot act.
You initialize the for
loop with int i = 0
then give bounds of i < 1
with an action if i
Given i
is type int with step of 1, it can never loop.