User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







c:control_structures:switch

This is an old revision of the document!


switch

description

The switch statement is a multi-select. An expression is evaluated once and compared to constants. In case of equality, the instructions that come after the constant processed. In switch statements can only ordinal data types (ie, int, long, int, char, etc.) use.

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.1358888546.txt · Last modified: 2024/02/16 01:02 (external edit)

Impressum Datenschutz