//오랜만에 써봅니다 수정 보완 지적 언제나 환영합니다!


다음과 같은 코드를 생각해보자

// test.cpp
#include <iostream>

int main(void) {
  int c = 2;

  switch (c) {
    case (1):
      std::cout << "case 1" << std::endl;
    case (2):
      std::cout << "case 2" << std::endl;
    case (3):
      std::cout << "case 3" << std::endl;
    default:
      std::cout << "case default" << std::endl;
      break;
  }
  return (0);
}

이를 다음과 같이 clang++로 컴파일하고 실행하면 아래와 같이 된다.

❯ clang++ -Wall -Wextra -Werror -std=c++98 test.cpp
❯ ./a.out
case 2
case 3
case default

switch case문은 일치하는 case를 실행한 후 이후 명령어들도 쭉 실행되게 되는데, 이를 fallthrough라고 한다. 따라서 이를 방지하기 위해서는 중간에 break나 return 등으로 빠져나와야한다.

그럼 위 코드를 g++ (gcc의 c++ 컴파일러)로 컴파일해보면 어떻게 될까?

❯ g++ -Wall -Wextra -Werror -std=c++98 test.cpp
test.cpp: In function ‘int main()’:
test.cpp:8:37: error: this statement may fall through [-Werror=implicit-fallthrough=]
    8 |       std::cout << "case 1" << std::endl;
      |                                     ^~~~
test.cpp:9:5: note: here
    9 |     case (2):
      |     ^~~~
test.cpp:10:37: error: this statement may fall through [-Werror=implicit-fallthrough=]
   10 |       std::cout << "case 2" << std::endl;
      |                                     ^~~~
test.cpp:11:5: note: here
   11 |     case (3):
      |     ^~~~
test.cpp:12:37: error: this statement may fall through [-Werror=implicit-fallthrough=]
   12 |       std::cout << "case 3" << std::endl;
      |                                     ^~~~
test.cpp:13:5: note: here
   13 |     default:
      |     ^~~~~~~
cc1plus: all warnings being treated as errors

이런식으로 fall through의 가능성이 있다고 implicit-fallthrough 옵션에 의해 warning이 뜨게 된다. (-Wextra 옵션이 -Wimplicit-fallthrough=3 옵션을 포함한다) 해당 fallthrough가 사용자가 의도한 것이 아닌, 실수일 가능성이 있다고 보고 경고해주는 것이다. 이를 통해 clang++과 g++ 등 컴파일러에 따라 띄워주는 경고가 다르다는 것을 알 수 있다. clang++에서는 기본적으로 -Wimplicit-fallthrough 옵션이 포함되지 않으며, clang++ -Wall -Wextra -Werror -Wimplicit-fallthrough 와 같이 명시적으로 넣어서 컴파일해야 경고가 뜬다.

(본 게시글에서는 g++ 11.3 버전을, clang++은 16.0 버전을 이용했다)