Currently, I write
assert(false);
at places that my code is never supposed to reach. One example, in a very C-ish style, is:
int findzero( int length, int * array ) {
for( int i = 0; i < length; i++ )
if( array[i] == 0 )
return i;
assert(false);
}
My compiler recognizes that the program finishes once assert(false) has been reached. However, whenever I compile with -DNDEBUG for performance reasons, the last assertion vanishes and the compiler warns that the execution finishes the function without a return statement.
What are better alternatives of finishing off a program if a supposedly unreachable part of the code has been reached? The solution should
- be recognized by the compiler and not produce warnings (like the ones above or others)
- perhaps even allow for a custom error message.
I am explicitly interested in solutions no matter whether it's modern C++ or like 90s C.
length
if nothing is found. The call site can check for that if they want and you don't get any warnings. – Sheleyabort()
? I am not sure if I understood the question correctly though – Platonism0
is truly not found in the array? You are assuming that0
is there somewhere. How is that guaranteed?? – Watchabort
is specifically about reaching something unreachable. I guess that#define unreachable_reached abort
would do it as well. – Agelessarray
stores, and he is responsible for asserting the impossible. Letfindzero
return an optional and assert on the call site. – Danny