---
# System prepended metadata

title: 'switch [C++]'
tags: [C]

---

# switch [C++]

## 宣告方法
> switch <output_type> function_name (<input_type>)

## 範例
- 當成function寫
```c
#include<iostream>

using namespace std;

class Solution
{ private:
    static int ConvertDigit(char c)
    {
        switch(c)
        {
            case'I':
                return 1;
            case'V':
                return 5;
            case'X':
                return 10;
            case'L':
                return 50;
            case'C':
                return 100:
            case'D':
                return 500;
            case'M':
                return 1000;
        }
        return 0;
    }
  
  public:
      int romanToInt(const string&s)
      {
          if (s.size() == 0) return 0;
          
          int currentDigit = convertDigit(s[s.size()-1]);
          int total = currentDigit;
          for(int i =s.size()-2; i>=0; --i)
          {
              int prevDigit = convertDigit(s[i]);
              if(prevDigit < currentDigit) total -= prevDigit;
              else{
                  total += prevDigit;
              }
              currentDigit = prevDigit;
          }
          return total;
      }
};

int main()
{
    Solution *s = new Solution();
    printf(%d, s->romanToInt("MCMXCIV"));
}
```
- 一般呼叫
```c
int main()
{
    char grade = 'D';
    
    switch(grade)
    {
        case 'A' :
          cout << "Excellent!" << endl; 
          break;
        case 'B' :
        case 'C' :
           cout << "Well done" << endl;
           break;
        case 'D' :
           cout << "You passed" << endl;
           break;
       case 'F' :
           cout << "Better try again" << endl;
           break;
        default :
           cout << "Invalid grade" << endl;
    }
       cout << "Your grade is " << grade << endl;

       return 0;
    }
}
```

<br>

###### tags: `C` 