In the book "The C programming language" its written that the last else statement in else-if construction can be used for error checking to catch an impossible condition.
Can anyone provide a simple example for this?
"Impossible" here means "shouldn't happen", not literally "can't happen", it being obviously pointless to check for the latter. In other words, you think you've written your code so that a variable can, at a given time, only have the values 1
, 2
or 3
, and you write your if
statements to handle them, but then add a final else
clause that does something to grab your attention so that if you're wrong, and your code is not as watertight as you thought, then you'll be able to see, and the bug won't just escape your attention.
For instance:
if ( val == 1 ) {
/* Do something normal */
} else if ( val == 2 ) {
/* Do something else normal */
} else if ( val == 3 ) {
/* Do something else else normal */
} else {
/* We shouldn't get here, but just in case we do... */
printf("ERROR - val has an unexpected value!\n");
exit(EXIT_FAILURE);
}
Maybe something like this:
int manipulteBit(int bit) {
if(bit == 0) {
//it's 0
//...
} else if(bit == 1) {
//it's 1
//...
} else {
//error, I expect 0 or 1
}
}
If you wrote a function that takes a number and should decide it it's 1 or 0, it should know how to deal with "invalid" input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With