Error: this statement may fall through [-Werror=implicit-fallthrough=]

agasim picture agasim · Apr 15, 2019 · Viewed 18.1k times · Source

I am trying to compile mitk on ubuntu and I got this error :

error: this statement may fall through [-Werror=implicit-fallthrough=]

Here there is a part of code :

      /** Get memory offset for a given image index */
      unsigned int GetOffset(const IndexType & idx) const
      {
       const unsigned int * imageDims = m_ImageDataItem->m_Dimensions;

        unsigned int offset = 0;
        switch(VDimension)
        {
        case 4:
         offset = offset + idx[3]*imageDims[0]*imageDims[1]*imageDims[2];
        case 3:
        offset = offset + idx[2]*imageDims[0]*imageDims[1];
        case 2:
        offset  = offset + idx[0] + idx[1]*imageDims[0];
         break;
        }

        return offset;
      }

I would be appreciate for any help please.

Answer

eerorika picture eerorika · Apr 15, 2019

Switch case statements will fall through by default. In the case of the shown program, if VDimension is 4 then all of

 offset = offset + idx[3]*imageDims[0]*imageDims[1]*imageDims[2];
offset = offset + idx[2]*imageDims[0]*imageDims[1];
offset  = offset + idx[0] + idx[1]*imageDims[0];

will be executed.

In some other languages, such as Pascal, only one case is executed and there is no concept of fall through. As such, programmers new to C++ may write fall through switches unintentionally.

If the fall through is unintentional, you need to add a break between each case to not fall through.

this statement may fall through

This warning notifies the programmer about the fall through. This warning option can be controlled with the GCC compiler switch -Wimplicit-fallthrough. It is not enabled by default and is not enabled by -Wall, but it is enabled by -Wextra.

Warnings become errors if the -Werror switch is used. -Werror is not enabled by default.

C++17 introduced [[fallthrough]] attribute, which can be used to explicitly document the fall through when it is intentional. The compiler should not warn if it is used.

Prior to C++17, GCC provides a language extension attribute __attribute__ ((fallthrough)) for the same purpose.

The fall through can also be documented with a comment, and Wimplicit-fallthrough may detect such comment depending on what value was used with the switch. More details in the documentation of GCC.