Latest web development tutorials

C ++ switch statement

C ++ judgment C ++ judgment

Test case aswitch statement allows a variable equal to the multiple value.Each value is called a case, and the variable will be tested eachswitch case to be checked.

grammar

Switch statement in C ++ syntax:

switch(expression){
    case constant-expression  :
       statement(s);
       break; // 可选的
    case constant-expression  :
       statement(s);
       break; // 可选的
  
    // 您可以有任意数量的 case 语句
    default : // 可选的
       statement(s);
}

switch statement must follow these rules:

  • switch statement expressionmust be an integer or enumeration type, or a class type, which class has a single conversion function to convert it to an integer or enumeration type.
  • In a switch you can have any number of case statements. Each case is followed by a value to compare with a colon.
  • case ofconstant-expression must have the same data type and switch variables, and it must be a constant or literal.
  • When the variable being tested is equal to the case of constant time, followed by a case statement will be executed, until it encounters abreak statement.
  • When abreak statement is encountered, switch terminates the control flow jumps to the next line after the switch statement.
  • Not every case needs to includebreak.If the case statement does not contain abreak, we willcontinueto control the flow of the subsequent case, until it encounters a break up.
  • Aswitch statement can have an optional default case,it appears at the end of the switch. default case can be used in all of the above case is not true when performing a task. Thebreak in the default case statement is not required.

flow chart

C ++ switch statement

Examples

#include <iostream>
using namespace std;
 
int main ()
{
   // 局部变量声明
   char grade = 'D';

   switch(grade)
   {
   case 'A' :
      cout << "很棒!" << endl; 
      break;
   case 'B' :
   case 'C' :
      cout << "做得好" << endl;
      break;
   case 'D' :
      cout << "您通过了" << endl;
      break;
   case 'F' :
      cout << "最好再试一下" << endl;
      break;
   default :
      cout << "无效的成绩" << endl;
   }
   cout << "您的成绩是 " << grade << endl;
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

您通过了
您的成绩是 D

C ++ judgment C ++ judgment