Here is a simplified case that would cause this warning, hopefully it will make the warning's meaning clear:
// Not allowed - Will cause the warning
int answer(int question)
{
if( question == 1 )
return 100;
else
if ( question == 2 )
return 200;
}
What if the question is not 1 and not 2?
For example, what if the value of question is 3, or 10?
What will the function return?
It is undefined, and illeal. This is what the warning means.
When a function which returns a value ends, the value that it returns must be defined for all cases.
But your case is more similar to this, which still produces the warning:
// Not allowed - still causes the warning
int max_of_two(int a, int b)
{
if( a>b )
return a;
else
if ( b>=a ) // we covered all logical cases, but compiler does not see that
return b;
}
You are probably saying to yourself, "But I did cover all the cases! No other case is possible!"
This is logically true, but the compiler does not know this. It does not build a logic table of all possible combinations of a>b, b<a etc.
So how can you correct this error? Make it more clear to the compiler that no other case is possible. In this case the correct code would be:
// OK - no warning
int max_of_two(int a, int b)
{
if( a>b )
return a;
else // The compiler now knows for sure that no other case is possible
return b;
}
The more interesting question is why does C++ let this off with a warning, and not produce a compiler error?
That question is discussed here:
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
... else { return 0; }
. – NutCrackertrue
. This is Undefined Behaviour. – Yksisarvinena
,b
,c
, andd
are all equal. – john