Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C switch Statement

C switch Statement

C Judgment C Judgment

The switch statement is a restricted control-flow statement used to execute different blocks of code based on the value of an expression.

A switch The statement allows testing a variable against several values; each value is called a case, and the tested variable is compared with each switch case .

Syntax

In the C language switch statement syntax:

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

)

;

}

Notes on the switch statement:

switch statements must follow these rules:

Flowchart

Example

#include

<

stdio.h

int

main

(

)

{

/*

Local variable definition

*/

char

grade

= '

B

';

switch

(

grade

)

{

case

'

A

' :

printf

(

"

Great!

\

n

"

)

;

break

;

case

'

B

' :

case

'

C

' :

printf

(

"

Well done

\

n

"

)

;

break

;

case

'

D

' :

printf

(

"

You passed

\

n

"

)

;

break

;

case

'

F

' :

printf

(

"

Better try again

\

n

"

)

;

break

;

default

:

printf

(

"

Invalid score

\

n

"

)

;

}

printf

(

"

Your grade is %c

\

n

"

,

grade

)

;

return

0

;

}

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



做得好

您的成绩是 B

C Judgment C Judgment