by Dinesh Thakur Category: Control Structures

No, but it is not a bad idea to put default statements in switch statements for error- or logic-checking

purposes. For instance, the following switch statement is perfectly normal:

 

switch (char_code)

{

case ‘Y’:

case ‘y’: printf(“You answered YES!\n”);

break;

case ‘N’:

case ‘n’: printf(“You answered NO!\n”);

break;

}

 

Consider, however, what would happen if an unknown character code were passed to this switch statement. The program would not print anything. It would be a good idea, therefore, to insert a default case where this condition would be taken care of:

...

default: printf(“Unknown response: %d\n”, char_code);

break;

...

 

Additionally, default cases come in handy for logic checking. For instance, if your switch statement handled a fixed number of conditions and you considered any value outside those conditions to be a logic error, you could insert a default case which would flag that condition. Consider the following example:

 

void move_cursor(int direction)

{

switch (direction)

{

case UP: cursor_up();

break;

case DOWN: cursor_down();

break;

case LEFT: cursor_left();

break;

case RIGHT: cursor_right();

break;

default: printf(“Logic error on line number %ld!!!\n”,

__LINE__);

break;

}

}

 



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content





Popular Article