Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - The switch statement

Node:The switch statement, Next:, Previous:The question mark operator, Up:Decisions



The switch statement

The switch construction is another way of making decisions in C code. It is very flexible, but only tests for integer and character values. It has the following general form:

switch (integer or character expression)
{
  case constant1 : statement1;
  break;          /* optional */

  case constant2 : statement2;
  break;          /* optional */

  case constant3 : statement3;
  break;          /* optional */
  ...
}

The integer or character expression in the parentheses is evaluated, and the program checks whether it matches one of the constants in the various cases listed. If there is a match, the statement following that case will be executed, and execution will continue until either a break statement or the closing curly bracket of the entire switch statement is encountered.

One of the cases is called default. Statements after the default case are executed when none of the other cases are satisfied. You only need a default case if you are not sure you are covering every case with the ones you list.

Here is an example program that uses the switch statement to translate decimal digits into Morse code:

 
 
  Published under free license. Design by Interspire