C++

C++ 스위치 문 총정리

김구티2 2024. 3. 12. 19:12

1. 스위치(Switch)문의 개념

C++ Switch 문은 주어진 식을 평가하고 평가된 값(특정 조건에 일치)에 따라 해당 식과 관련된 문을 실행한다. 이는 긴 if-else-if 사다리의 대안으로, 식의 값을 기반으로 실행을 코드의 여러 부분으로 쉽게 보낼 수 있다. 즉, 주어진 식의 값을 기반으로 문장의 여러 블록을 실행하는 데 사용되는 흐름 제어 문인 것이다. 스위치 문에 임의의 수의 케이스를 지정할 수 있지만, 경우 값은 int 또는 char 형식만 사용할 수 있다.

 

구문:

switch (expression) {
    case value_1:
        // statements_1;
        break;
    case value_2:
        // statements_2;
        break;
    .....
    .....
    default:
        // default_statements;
        break;
}

 

예시:

// C++ program to demonstrate syntax of switch
#include <iostream>
using namespace std;

// Driver Code
int main()
{
      // switch variable
      char x = 'A';

      // switch statements
      switch (x) {
      case 'A':
            cout << "Choice is A";
            break;
      case 'B':
            cout << "Choice is B";
            break;
      case 'C':
            cout << "Choice is C";
            break;
      default:
            cout << "Choice other than A, B and C";
            break;
}
      return 0;
}

 

출력:

Choice is A

2. 스위치 문에서의 규칙

① 대소문자 값은 int 또는 char type이어야 한다.
② 몇 가지 케이스가 존재할 수 있다.
③ 중복되는 대소문자 값은 허용되지 않는다.
④ 각 statement에는 break가 있을 수 있으며, 이는 선택사항이다.
⑤ default statement도 선택 사항이다.

3. 스위치 문 흐름도

4. 스위치 문의 다양한 예시

break가 없는 예시:

// C Program to demonstrate the behaviour of switch case
// without break
#include <stdio.h>

int main()
{

     int var = 2;

     // switch case without break
     switch (var) {
     case 1:
          printf("Case 1 is executed.\n");
     case 2:
          printf("Case 2 is executed.\n");
     case 3:
          printf("Case 3 is executed.\n");
     case 4:
          printf("Case 4 is executed.");
}
     return 0;
}

 

출력:

Case 2 is executed.
Case 3 is executed.
Case 4 is executed.

 

중첩 스위치 문 예시:

// C program to illustrate the use of nested switch
#include <iostream>
using namespace std;

int main()
{

     int var1 = 1;
     int var2 = 0;

     // outer switch
     switch (var1) {
     case 0:
          cout << "Outer Switch Case 0\n";
          break;
     case 1:
          cout << "Outer Switch Case 1\n";
          // inner switch
          switch (var2) {
          case 0:
               cout << "Inner Switch Case 0\n";
               break;
          }
          break;
     default:
          cout << "Default Case of Outer Loop";
          break;
     }

     return 0;
}

 

출력:

Outer Switch Case 1
Inner Switch Case 0

 

스위치를 이용한 계산기 프로그래밍 예시:

// C Program to create a simpe calculator using switch
// statement
#include <iostream>
#include <stdlib.h>
using namespace std;

// driver code
int main()
{
     // switch variable
     char choice;
     // operands
     int x, y;

     while (1) {
          cout << "Enter the Operator (+,-,*,/)\nEnter x to "
                       "exit\n";
          cin >> choice;

          // for exit
          if (choice == 'x') {
               exit(0);
          }

          cout << "Enter the two numbers: ";
          cin >> x >> y;

          // switch case with operation for each operator
          switch (choice) {
          case '+':
               cout << x << " + " << y << " = " << x + y
                       << endl;
               break;

          case '-':
               cout << x << " - " << y << " = " << x - y
                      << endl;
               break;

          case '*':
               cout << x << " * " << y << " = " << x * y
                       << endl;
               break;
          case '/':
               cout << x << " / " << y << " = " << x / y
                       << endl;
               break;
          default:
               printf("Invalid Operator Input\n");
          }
     }
     return 0;
}

 

출력:

Enter the operator (+, -, *, /)

Enter x to exit

+
Enter the two numbers: 100 + 200
100 + 200 = 300

 

스위치를 이용한 요일 표시 예시:

// C++ program to returns day based on the numeric value.
#include <iostream>
using namespace std;

class Day {
private:
     int day = 3;

public:
     void set_data()
     {
          cout << "Enter no of day you want to display: ";
          cin >> day;
     }

     void display_day()
     {
          switch (day) {
          case 1:
               cout << "MONDAY";
               break;

          case 2:
               cout << "TUESDAY";
               break;

          case 3:
               cout << "WEDNESDAY";
               break;

          case 4:
               cout << "THURSDAY";
               break;

          case 5:
               cout << "FRIDAY";
               break;

          case 6:
               cout << "SATURDAY";
               break;

          case 7:
               cout << "SUNDAY";
               break;

          default:
               cout << "INVALID INPUT";
               break;
          }
     }
};

main()
{
     Day d1;

     d1.display_day();

     return 0;
}

 

출력:

WEDNESDAY

 

enum 값과 클래스를 사용하여 다양한 선택 사항을 프린트하는 프로그래밍 예시:

#include <iostream>
#include <map>
#include <string>

// Define an enum class for the choices
enum class Choice { A, B, C };

// Create a map to associate strings with the enum values
std::map<std::string, Choice> stringToEnumMap
     = { { "A", Choice::A },
         "B", Choice::B },
         "C", Choice::C } };

int main()
{
     // The input string
     std::string x = "A";

     // Convert the string to the corresponding enum using
     // the map
     Choice choice = stringToEnumMap[x];

     // Use a switch statement on the enum
     switch (choice) {
     case Choice::A:
          std::cout << "Choice is A";
          break;
     case Choice::B:
          std::cout << "Choice is B";
          break;
     case Choice::C:
          std::cout << "Choice is C";
          break;
     default:
          std::cout << "Choice other than A, B and C";
          break;
     }

     return 0;
}

/* The enum class can be used for choice sets
from different projects or programs, 
hence improving modularity*/

 

출력:

Choice is A

5. 스위치 문의 장단점

장점 ① 많은 수의 조건에 대해 더 쉽게 디버깅하고 유지 관리할 수 있다.

장점 ② if else if에 비해 더욱 읽기 수월하다.

단점 ① 스위치 문은 int나 char 타입만 가능하다는 것이 단점이다.

단점 ② 논리식을 지원하지 않는다.

단점 ③ 모든 경우에 break를 추가해야 한다는 것을 염두에 두어야 한다.

728x90

'C++' 카테고리의 다른 글

C++ for, while, do while 루프(Loop) 총정리  (1) 2024.03.14
C++ 점프문 총정리  (1) 2024.03.14
C++ Nested if문(중첩 if문) 총정리  (0) 2024.03.10
C++ if else if 총정리  (0) 2024.03.10
C++ 조정자(Manipulator) 총정리  (0) 2024.03.10