User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







c:control_structures:switch

switch

description

The switch statement is a multi-select control structure. An expression is evaluated once and compared to 'constants'. In case of equality, the 'statements' that come after the 'constant' are processed. In switch 'statements' can only ordinary data types (ie, 'int', 'long', char, short, etc.) can be used.

switch(expression)
{
   case constant1:
       statements
   break;
 
   case constant2:
       statements
   break;
 
   case constantn:
       statements
   break;
 
   default:
       statements
} 

switch example in c

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 int input;
 
    do
    {
        printf( "press 1 or 2 \n" );
        scanf( "%d", &input );
        switch ( input ) 
        {
            case 1:
                printf("case 1 selected\n");
                break;
            case 2:          
                printf("case 2 selected\n");
                break;
            default:            
                printf( "default case!\n" );
                break;
        }
    }
    while(input != 2);
 
return 0;
}

output of this switch example

  press 1 or 2 
  1
  case 1 selected
  press 1 or 2 
  2
  case 2 selected

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
c/control_structures/switch.txt · Last modified: 2024/02/16 01:04 (external edit)

Impressum Datenschutz