Error this statement may fall through werror implicit fallthrough

I have git master up-to-date as at 2017-02-14T08:13+00:00, with Fedora Rawhide fully up to date, and attempt to build Pony results in: |> make Makefile:224: WARNING: Unsupported LLVM version: 3....

@sylvanc @jemc Closing this was premature, I’m afraid. I pulled to bfb4b94 and then:

|> make
Makefile:224: WARNING: Unsupported LLVM version: 3.9.0
Makefile:225: Please use LLVM 3.7.1, 3.8.1, or 3.9.1
actor.c
messageq.c
fun.c
src/libponyrt/ds/fun.c: In function ‘siphash24’:
src/libponyrt/ds/fun.c:46:15: error: this statement may fall through [-Werror=implicit-fallthrough=]
     case 7: b |= ((uint64_t)in[6]) << 48; // -fallthrough
             ~~^~~~~~~~~~~~~~~~~~~~~~~~~~
src/libponyrt/ds/fun.c:47:5: note: here
     case 6: b |= ((uint64_t)in[5]) << 40; // -fallthrough
     ^~~~
src/libponyrt/ds/fun.c:47:15: error: this statement may fall through [-Werror=implicit-fallthrough=]
     case 6: b |= ((uint64_t)in[5]) << 40; // -fallthrough
             ~~^~~~~~~~~~~~~~~~~~~~~~~~~~
src/libponyrt/ds/fun.c:48:5: note: here
     case 5: b |= ((uint64_t)in[4]) << 32; // -fallthrough
     ^~~~
src/libponyrt/ds/fun.c:48:15: error: this statement may fall through [-Werror=implicit-fallthrough=]
     case 5: b |= ((uint64_t)in[4]) << 32; // -fallthrough
             ~~^~~~~~~~~~~~~~~~~~~~~~~~~~
src/libponyrt/ds/fun.c:49:5: note: here
     case 4: b |= ((uint64_t)in[3]) << 24; // -fallthrough
     ^~~~
src/libponyrt/ds/fun.c:49:15: error: this statement may fall through [-Werror=implicit-fallthrough=]
     case 4: b |= ((uint64_t)in[3]) << 24; // -fallthrough
             ~~^~~~~~~~~~~~~~~~~~~~~~~~~~
src/libponyrt/ds/fun.c:50:5: note: here
     case 3: b |= ((uint64_t)in[2]) << 16; // -fallthrough
     ^~~~
src/libponyrt/ds/fun.c:50:15: error: this statement may fall through [-Werror=implicit-fallthrough=]
     case 3: b |= ((uint64_t)in[2]) << 16; // -fallthrough
             ~~^~~~~~~~~~~~~~~~~~~~~~~~~~
src/libponyrt/ds/fun.c:51:5: note: here
     case 2: b |= ((uint64_t)in[1]) << 8;  // -fallthrough
     ^~~~
src/libponyrt/ds/fun.c:51:15: error: this statement may fall through [-Werror=implicit-fallthrough=]
     case 2: b |= ((uint64_t)in[1]) << 8;  // -fallthrough
             ~~^~~~~~~~~~~~~~~~~~~~~~~~~
src/libponyrt/ds/fun.c:52:5: note: here
     case 1: b |= ((uint64_t)in[0]);
     ^~~~
cc1: all warnings being treated as errors
|> gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/7/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-redhat-linux
Configured with: ../configure --enable-bootstrap --enable-languages=c,c++,objc,obj-c++,fortran,ada,go,lto --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-shared --enable-threads=posix --enable-checking=release --enable-multilib --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --with-gcc-major-version-only --with-linker-hash-style=gnu --enable-plugin --enable-initfini-array --with-isl --enable-libmpx --enable-offload-targets=nvptx-none --without-cuda-driver --enable-gnu-indirect-function --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
Thread model: posix
gcc version 7.0.1 20170204 (Red Hat 7.0.1-0.6) (GCC) 

(See this article to install GCC 7 on Red Hat Enterprise Linux.)

In C and C++, the cases of a switch statement are in fact labels, and the switch is essentially a go to that jumps to the desired label. Since labels do not change the flow of control, one case block falls through to the following case block, unless terminated by a return, a break, a no return call or similar. In the example below, «case 1» falls through to «case 2«:

switch (cond)
   {
   case 1:
     a = 1;
   case 2:
     a = 2;
     break;
   /* ... */
   }

The switch fallthrough has been widely considered a design defect in C, a misfeature or, to use Marshall Cline’s definition, evil [1]. An overwhelming majority of the time the fallthrough to the next case is not appropriate, and it’s easy to forget to «break» at the end of a case, making this far too error prone. Yet GCC didn’t have the ability to warn for undesirable fallthroughs. A feature request for such a warning was opened back in 2002, but it didn’t get much attention for the next 14 years. But then the [[fallthrough]] attribute was approved for C++17 [2], the request gained more traction, and I decided to take on this project. Although my first attempts flopped, in the end, I was successful in getting all the pieces in place, and with help from other GCC developers, we were able to implement -Wimplicit-fallthrough. In the following article, I will attempt to describe the warning in more detail.

The warning is enabled by -Wextra for C and C++. In the original test case above -Wimplicit-fallthrough will warn about «a = 1;» falling through to «case 2» like this:

z.c: In function ‘f’:
z.c:7:9: warning: this statement may fall through [-Wimplicit-fallthrough=]
 a = 1;
 ~~^~~
z.c:8:5: note: here
 case 2:
 ^~~~

The warning is able to cope with various control-flow statements, nested scopes, gotos, and similar, and should only warn when appropriate. Consider the following snippet:

switch (cond)
  {
  case 1:
    if (n > 20)
      return;
    else if (n > 10)
      {
        foo (9);
        break;
      }
    else
      foo (8); // warn here
  case 2:
  /* ... */
  }

Here the compiler is smart enough to figure out that only the third branch can actually fall through, and the diagnostic is only given for the «foo (8);» statement. Naturally, since the warning occurs at compile-time, rather than at run-time, it’s not totally foolproof since it’s not possible for the warning to determine in all cases if the loop can terminate or not.

To further reduce the rate of false positives, the warning will not warn when the last statement of a case block cannot fall through, as it happens e.g. for noreturn calls, as demonstrated in the example below:

 __attribute__((noreturn)) void die (void);
 
 switch (cond)
   {
   case -1:
     die ();
   case 0:
   /* ... */
   }

The warning is also suppressed when a case label falls through to a case that merely breaks or returns:

switch (cond)
 {
 case -1:
   foo ();
 default:
   break;
 }

Since there are occasions where a switch case fallthrough is desirable, GCC provides several ways to quiet the warning that would otherwise occur. The first option is to use a null statement («;«) with the fallthrough attribute. As mentioned before, C++17 provides a standard way to suppress the warning by
using «[[fallthrough]];» instead of the non-standard way above with the GNU attribute. In C++11 and C++14 users can still use the [[…]] notation, only with the gnu:: prefix. In C++03 users will have to revert to the C way. (There is a proposal to add the [[...]] attribute syntax to C2X [3].)
To summarize:

switch (cond)
 {
 case 1:
   bar (1);
   __attribute__ ((fallthrough)); // C and C++03
 case 2:
   bar (2);
   [[gnu::fallthrough]]; // C++11 and C++14
 case 3:
   bar (3);
   [[fallthrough]]; // C++17 and above
 /* ... */
 }

Of course, existing programs will be missing the smarts above to suppress the warning, and so enabling the warning would cause more harm than good. To reduce the annoyance when porting to GCC 7, we decided to recognize a wide variety of «falls through» comments. We hope that the code bases that use these comments consistently won’t have to worry about turning on -Wimplicit-fallthrough.

The range and shape of «falls through» comments accepted are contingent upon the level of the warning. (The default level is =3.)

  • -Wimplicit-fallthrough=0 disables the warning altogether.
  • -Wimplicit-fallthrough=1 treats any kind of comment as a «falls through» comment.
  • -Wimplicit-fallthrough=2 essentially accepts any comment that contains something that matches (case insensitively) «falls?[ t-]*thr(ough|u)» regular expression.
  • -Wimplicit-fallthrough=3 case sensitively matches a wide range of regular expressions, listed in the GCC manual. E.g., all of these are accepted:
    /* Falls through. */
    /* fall-thru */
    /* Else falls through. */
    /* FALLTHRU */
    /* … falls through … */
    etc.
  • -Wimplicit-fallthrough=4 also, case sensitively matches a range of regular expressions but is much more strict than level =3.
  • -Wimplicit-fallthrough=5 doesn’t recognize any comments.

Note that the attributes are recognized on any level.

For a more detailed description of the regular expressions accepted, please see the GCC manual [4].

These «falls through» comments are meant to be used as in the example here:

switch (cond)
 {
 case 0:
   foo (0);
   /* FALLTHRU */
 case 1:
   foo (1); 
   /* further code */
 }

I.e., they should precede the case or default keywords. Be aware though that they might clash with macros so sometimes using the attributes will be necessary.

References

[1] http://www.cs.technion.ac.il/users/yechiel/c++-faq/defn-evil.html
[2] http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0188r0.pdf
[3] http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2052.pdf
[4] https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html


You can easily install GCC 7 on Red Hat Enterprise Linux using yum. GCC 7.3 was included in the May 2018 of Red Hat Developer Toolset (DTS). DTS provides the latest stable compilers and is part of the no-cost developer subscription.

Last updated:
October 18, 2018

MiK13 писал: ↑

21.01.2020 16:11


Но это, скорее всего приведёт к дублированию вызовов.

Не обязательно.

MiK13 писал: ↑

21.01.2020 16:11


У меня при обработке запроса надо добавить в некоторый массив группу данных. Или просто занести.
Второе действие представляет собой первое, только с предварительной очисткой массива.

Ну что ж, позвольте изложить чуть подробнее.
Книг по языку Си я видел не очень много, но штук пять-шесть навскидку могу припомнить.
И практически везде наблюдалась одна и та же картина: оператор switch вводится после if…else
примерно в таком контексте: вот у нас есть несколько условий (штук десять), if…else (который мы уже знаем) использовать неудобно, слишком громоздкая конструкция получается, поэтому вот вам switch.
То есть switch и if…else делают примерно одно и то же.
И если это так, то отсюда следуют две вещи:
1. Условия в switch взаимоисключающие.
2. В случае небольшого количества условий можно обойтись if…else.

В Вашем случае условия в switch взаимоисключающими не являются, насколько я понял.
Это уже повод пересмотреть код. Ну и по количеству условий — оно мне неизвестно, но может оказаться, что switсh вообще не нужен.

Можно либо иначе сформулировать условия, сделав их взаимоисключающими,
либо вообще не использовать switch.
Если Clear() вызывается только как предварительное действие к Store(),
но никогда не вызывается сама по себе, то отдельная ветка в switch ей нафиг не нужна — много чести.
В этом случае я бы её вызывал где-нибудь внутри Store() в нужный момент (при нужных условиях).

MiK13 писал: ↑

21.01.2020 16:11


Войны с компилятором нет.

Ну, хорошо, не война. Возня.
Сборка прошла с предупреждением, что-то подшаманили, предупреждение исчезло,
пришли на другую машину/другой дистр/другую разрядность/другую версию — предупреждение опять появилось,
опять нужно шаманить, только уже иначе ну и т.д.
А всего-то и надо было, что отрефакторить несколько строк кода с учётом особенностей языка.

Я сам люблю, когда сборка происходит «чисто» — без предупреждений. И стараюсь этого добиться.
А в некоторых проектах, которые я видел, вообще всё сурово: предупреждения приравнены к ошибкам.
Были такие давние времена, когда в случае ошибок сборки исправляли компилятор, а не программу.
И эти интересные люди вроде бы даже ещё живы.
А мы с Вами сегодня можем позволить себе роскошь доверять компилятору.
И если уж мы обращаем внимание на его сообщения, то не зря же мы это делаем.
Мы же хотим наш код улучшить, а не просто «подавляющих атрибутов» напихать.
Таково моё ИМХО.

Понравилась статья? Поделить с друзьями:
  • Error this server is already on your list ok
  • Error this script needs bsddb3 to be installed
  • Error this script must be started from web server s document root
  • Error this script can only be executed by root
  • Error this page has been moved to trash bin перевод