Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an explicit fall-through in C

The newer versions of gcc offer the Wimplicit-fallthrough, which is great to have for most switch statements. However, I have one switch statement where I want to allow fall throughs from all case-statements.

Is there a way to do an explicit fall through? I'd prefer to avoid having to compile with Wno-implicit-fallthrough for this file.

EDIT: I'm looking for a way to make the fall through explicit (if it's possible), not to turn off the warning via a compiler switch or pragma.

like image 854
dlasalle Avatar asked Jun 13 '17 02:06

dlasalle


People also ask

What is a fall through in C?

Fall through is a type of error that occurs in various programming languages like C, C++, Java, Dart …etc. It occurs in switch-case statements where when we forget to add a break statement and in that case flow of control jumps to the next line.

Where is [[ Fallthrough ]] used?

A fallthrough statement may only be used in a switch statement, where the next statement to be executed is a statement with a case or default label for that switch statement.

What is implicit Fallthrough?

Implicit fallthrough is when control flow transfers from one switch case directly into a following switch case without the use of the [[fallthrough]]; statement. This warning is raised when an implicit fallthrough is detected in a switch case containing at least one statement.

What is fall through behavior in C++?

C++ Attributes [[fallthrough]]Whenever a case is ended in a switch , the code of the next case will get executed. This last one can be prevented by using the ´break` statement. As this so-called fallthrough behavior can introduce bugs when not intended, several compilers and static analyzers give a warning on this.


1 Answers

Use __attribute__ ((fallthrough))

switch (condition) {     case 1:         printf("1 ");         __attribute__ ((fallthrough));     case 2:         printf("2 ");         __attribute__ ((fallthrough));     case 3:         printf("3\n");         break; } 
like image 143
Sergey Kalinichenko Avatar answered Oct 11 '22 04:10

Sergey Kalinichenko