Assuming this example code (source):
#include <stdio.h>
void playgame()
{
printf( "Play game called" );
}
void loadgame()
{
printf( "Load game called" );
}
void playmultiplayer()
{
printf( "Play multiplayer game called" );
}
int main()
{
int input;
printf( "1. Play game\n" );
printf( "2. Load game\n" );
printf( "3. Play multiplayer\n" );
printf( "4. Exit\n" );
printf( "Selection: " );
scanf( "%d", &input );
switch ( input ) {
case 1: /* Note the colon, not a semicolon */
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
printf( "Thanks for playing!\n" );
break;
default:
printf( "Bad input, quitting!\n" );
break;
}
getchar();
return 0;
}
should we use a break;
in the last default
case? If I remove it, I see the same behaviour of the program. However, I saw that other examples also use a break;
in the default
case.
Why? Is there a reason?
break
after any case label if it is the last one. Whether it isdefault
or otherwise has nothing to do with that.-pedantic
recent versions of gcc warn about a missingbreak
after the lastcase
.gcc -std=c99 -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.c"
. Maybe-Wall
was enough for that.