Home >Backend Development >C++ >switch case statement in C language

switch case statement in C language

WBOY
WBOYforward
2023-08-28 11:17:02893browse

The

在C语言中的switch case语句

#switch statement allows testing of a variable for equality with a list of values. Each value is called a case, and the variable being opened is checked against each switch case.

The syntax of switch statement in C programming language is as follows- p>

switch(expression) {
   case constant-expression :
      statement(s);
      break; /* optional */
   case constant-expression :
      statement(s);
      break; /* optional */
      /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

The following rules apply to switch statement-

  • switch The expression statement used must have an integral or enumeration type, or be a class type where the class has a single conversion function to an integral or enumeration type.

  • You can have any number switch in the case statement. Each case is followed by the value to be compared and a colon.

  • The constant expression of the instance must be of the same data type as the variable in switch, which must be a constant or a literal.

  • When the variable being switched is equal to a case, the statements following the case will be executed until the break statement is reached.

  • When the break statement is reached, the switch terminates and the flow of control jumps to the next line after the switch statement.

  • Not every case needs to contain break. If no interrupt occurs, control flow will proceed to subsequent situations until an interrupt is reached.

  • The switch statement can have an optional default case, which must appear at the end of the switch. A default case can be used to perform a task when all else fails. Interrupts are not required by default.

Sample code

Real-time demonstration

#include <stdio.h>
int main () {
   /* local variable definition */
   char grade = &#39;B&#39;;
   switch(grade) {
      case &#39;A&#39; :
         printf("Excellent!</p><p>" );
         break;
      case &#39;B&#39; :
      case &#39;C&#39; :
         printf("Well done</p><p>" );
         break;
      case &#39;D&#39; :
         printf("You passed</p><p>" );
         break;
      case &#39;F&#39; :
         printf("Better try again</p><p>" );
         break;
      default :
         printf("Invalid grade</p><p>" );
   }
   printf("Your grade is %c</p><p>", grade );
   return 0;
}

Output

Well done
Your grade is B

The above is the detailed content of switch case statement in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete