Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of the last else statement in Else-If construction

Tags:

c

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?

like image 309
user239321 Avatar asked Feb 13 '23 20:02

user239321


2 Answers

"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);
}
like image 161
Crowman Avatar answered Mar 05 '23 13:03

Crowman


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.

like image 45
Maroun Avatar answered Mar 05 '23 12:03

Maroun