Home  >  Article  >  Backend Development  >  c++ switch usage

c++ switch usage

藏色散人
藏色散人Original
2020-05-29 09:12:056275browse

c++ switch usage

A switch statement allows testing of a variable equal to multiple values. Each value is called a case, and the variable being tested checks each switch case.

Grammar

The syntax of the switch statement in C:

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

The switch statement must follow the following rules:

The expression in the switch statement must be an integer type or enumeration type, or a class type where class has a single conversion function to convert it to an integer or enumeration type.

There can be any number of case statements in a switch. Each case is followed by a value to be compared and a colon. The constant-expression of

case must have the same data type as the variable in switch, and must be a constant or literal.

When the variable being tested is equal to the constant in the case, the statements following the case will be executed until a break statement is encountered.

When a break statement is encountered, the switch terminates and the control flow will jump to the next line after the switch statement.

Not every case needs to include break. If the case statement does not contain a break, control flow will continue with subsequent cases until a break is encountered.

A switch statement can have an optional default case, which appears at the end of the switch. The default case can be used to perform a task when none of the above cases are true. The break statement in the default case is not required.

c++ switch usage

The above is the detailed content of c++ switch usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn