View the Most Wanted LQ Wiki articles.
LinuxQuestions.org > Linux Wiki > Fall through

From LQWiki

Jump to: navigation, search

In the C programming language, fall-through is a term describing the behavior of a programming construct such as the switch() statement. switch()'s job is to check an expression and execute a certain piece of code depending on the value which the expression yields:

switch (x) {

   case 0:
       puts("0");
   case 1:
       puts("1");
       break;
   case 2:
       puts("2");
       break;
   default:
       puts("unknown");

}

The code will jump to the different case: labels depending on the value of x. Execution then resumes from the case: label. The break; statements cause the execution to jump to the end of the switch() statement. A typical programming error in writing switch() statements is to omit a break; statement from one of the clauses where one was intended. This causes the execution to "fall-through" to successive code in the switch() statement. (In the example above, case 0: has no break; statement, and so when (x == 0) the switch() statement will print "01")

The key to understanding the switch() statement and the fall-through is that case: labels are essentially the same as a label you would use for the goto statement. They are merely a marker for a place for execution to jump. They do not in any way partition the code withing the switch() statement. With proper understanding of that principle, the fall-through effect can be used for practical benefit, as in Duff's_device


Personal tools