ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 'if' you wanna 'switch' something
    개발/C++ 2021. 4. 6. 16:57
    switch (char ch; int count = scanf("%c", &ch))
    	{
    		case 'A':			
    		case 'a':
    			cout << "It's a" << endl;
    			break;
    		case 'b':
    			cout << ch << endl;
    			break;
    		default:
    			cout << "Invalid input" << endl;
    
    	}

    C++17부터 if문의 조건에 초기화 구문을 넣을 수 있습니다. 변수 선언도 당연히 가능하구요. 조건문 안에 선언된 변수는 else문에서도 접근 가능합니다.

     

    switch 구문을 사용할 때 의도적으로 break를 안 쓰는 경우가 있습니다. 추가적인 코드를 넣지 않는 경우에는 경고가 일어나지 않고 가독성에도 별 문제가 없습니다만,

    #include <iostream>
    using namespace std;
    
    int main()
    {
    	switch (char ch; int count = scanf("%c", &ch))
    	{
    		case 'A':			
    		case 'a':
    			cout << "It's a" << endl;
    			break;
    		default:
    			cout << "Invalid input" << endl;
    	}
    }

     

    statement가 들어가있을 경우에는 [[fallthrough]]을 넣어야 경고가 뜨지 않으며 가독성에도 좋습니다. 의도한 것임을 알 수 있기 때문입니다. 비주얼 스튜디오에서는 [[fallthrough]]를 넣지 않아도 경고가 뜨지 않습니다만, gcc에서는 [[fallthrough]]가 없으면 경고를 띄워 줍니다.

    #include <iostream>
    using namespace std;
    
    int main()
    {
    	switch (char ch; int count = scanf("%c", &ch))
    	{
    		case 'A':
    			cout << "Converted to a" << endl;
    			[[fallthrough]];
    		case 'a':
    			cout << "It's a" << endl;
    			break;
    		default:
    			cout << "Invalid input" << endl;
    
    	}
    }

     

    '개발 > C++' 카테고리의 다른 글

    [Enum] 가독성을 위한 약간의 수고  (0) 2021.04.09
    [Cache] 시간 지역성, 공간 지역성  (0) 2021.04.08
    음수 표현(feat.2의 보수)  (0) 2021.04.03
    Sequence point  (0) 2021.03.30
    [cin] 입력 실패를 처리하는 법  (0) 2021.03.29

    댓글

Designed by Tistory.