next up previous contents
Next: nested switch statements Up: 判斷 Previous: if...else if...else Statement   Contents

switch statement

  1. 流程圖

    \begin{tikzpicture}[node distance=1.3cm]\setlength \baselineskip{1ex}
\node [input,name=input] {};
\node [decision, below of=input] (decision) {expression?};
\node [input,below of=decision] (input1) {};
\node [block, right of=input1,node distance=4cm] (block1) {code block 1};
\node [input,below of=input1] (input2) {};
\node [block, right of=input2,node distance=4cm] (block2) {code block 2};
\node [cir, right of=block2,node distance=3cm] (sum2) {};
\node [input,below of=input2] (input3) {};
\node [block, right of=input3,node distance=4cm] (block3) {code block 3};
\node [cir, right of=block3,node distance=3cm] (sum3) {};
\node [,below of=sum3,node distance=0.5cm] (omit2) {$\vdots$};
\node [,below of=input3,node distance=0.5cm] (omit1) {$\vdots$};
\node [input,below of=omit1] (inputd) {};
\node [block, right of=inputd,node distance=4cm] (blockd) {code block N};
\node [cir, below of=omit2] (sumd) {};
\node [output,below of=sumd] (output) {};
\par
\path [line] (input) --(decision);
\path [line] (decision) --(input1);
\path [line] (input1) -- node[above]{case 1}(block1);
\path [line] (input1) --(input2);
\path [line] (block1.east) -\vert (sum2.north);
\path [line] (input2) -- node[above]{case 2}(block2);
\path [line] (input2) --(input3);
\path [line] (block2) --(sum2);
\path [line] (sum2) -- (sum3.north);
\path [line] (input3) -- node[above]{case 3}(block3);
\path [line] (block3) --(sum3);
\path [line] (omit1) -- (inputd);
\path [line] (omit2) -- (sumd.north);
\path [line] (inputd) -- node[above]{default}(blockd);
\path [line] (blockd) --(sumd);
\path [line] (sumd) --(output);
\end{tikzpicture}

  2. 語法:break 可有可無,有沒有 break 有何差別?
    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);
    }
    
  3. 範例
    #include <stdio.h>
     
    int main ()
    {
       /* local variable definition */
       char grade = 'B';
    
       switch(grade)
       {
       case 'A' :
          printf("Excellent!\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 grade\n" );
       }
       printf("Your grade is  %c\n", grade );
     
       return 0;
    }
    



2015-01-16