C Switch Case

Switch case statements are a substitute for long if statements that compare a variable to several "integral" values.

Example 1

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 int input;
 
    do
    {
 
        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 */
             printf("Playing the game\n");
             break;
            case 2:          
                printf("Loading the game\n");
                break;
            case 3:         
                printf("Playing multiplayer\n");
                break;
            case 4:        
                printf( "Thanks for playing!\n" );
                break;
            default:            
                printf( "Bad input!\n" );
                break;
        }
    }while(input != 4);
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.