The switch and case statements help control complex conditional and branching operations. The switch statement transfers control to a statement within its body.
Syntax
selection-statement:
switch ( expression ) statementlabeled-statement:
{
case constant-expression : statement
default : statement
}
Control passes to the statement whose case constant-expression matches the value of switch ( expression ). The switch statement can include any number of case instances, but no two case constants within the same switchstatement can have the same value. Execution of the statement body begins at the selected statement and proceeds until the end of the body or until a break statement transfers control out of the body.
Use of the switch statement usually looks something like this:
switch ( expression )
{
declarations
.case constant-expression :
statements executed if the expression equals the
value of this constant-expression
.
break;
default :
statements executed if expression does not equal any case constant-expression
}
declarations
.case constant-expression :
statements executed if the expression equals the
value of this constant-expression
.
break;
default :
statements executed if expression does not equal any case constant-expression
}
#include <stdio.h>
#include<conio.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;
}
getch();
}
No comments:
Post a Comment