Omitting break Statements from a switch Statement

Don't forget to include break statements when using the switch statement:

switch( ch )

{

case 'e':

printf( "Bye bye\n" );

break;

case 'l':

printf( "Loading the file\n" );

load_file( fp );

break;

case 's':

printf( "Saving the file\n" );

write_file( fp ); /* Error! Missing break. */

case 'd':

printf( "Deleting the file\n" );

kill_file( fp );

break;

default:

break;

}

In this code a break statement is missing from the statements following the third case label (the statements that print Saving the file ). After those statements execute, execution falls through to the next case label, deleting the newly saved file.

To avoid this problem, place a break at the end of every case item:

case 's':

printf( "Saving the file.\n" );

write_file( fp );

break;

It's legal, of course, to write a program in which execution deliberately falls through from one case label to the next. In such cases you may want to add a comment to prevent confusion.