DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Implicit Fallthrough in GCC 7

The switch fallthrough has been widely considered a design defect in C. An overwhelming majority of the time, the fall-through to the next case is not appropriate.

Marek Polacek user avatar by
Marek Polacek
·
Mar. 13, 17 · Opinion
Like (2)
Save
Tweet
Share
13.10K Views

Join the DZone community and get the full member experience.

Join For Free

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. An overwhelming majority of the time, the fall-through 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, 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, i.e., for no return 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 fall through 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.)

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.

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 */
 }

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.

GNU Compiler Collection code style

Published at DZone with permission of Marek Polacek, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 5 Recent Amazing AI Advancements
  • Web Testing Tutorial: Comprehensive Guide With Best Practices
  • Leverage Lambdas for Cleaner Code
  • Effective Jira Test Management

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: