````

Arduino - switch case statement

Similar to the if statements, switch...case controls the flow of programs by allowing the programmers to specify different codes that should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in the case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run.
The break keyword makes the switch statement exit, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached.

Switch Case Statement Syntax

switch (variable) { 
   case label:
   // statements
   break;
}

case label: { 
   // statements
   break;
}

default: { 
   // statements
   break;
}

Switch Case Statement Execution Sequence

Switch Case Statement

Example

Here is a simple example with switch. Suppose we have a variable phase with only 3 different states (0, 1, or 2) and a corresponding function (event) for each of these states. This is how we could switch the code to the appropriate routine −
switch (phase) {
   case 0: Lo(); break;
   case 1: Mid(); break;
   case 2: Hi(); break;
   default: Message("Invalid state!");
}

Related Posts:

  • What is power electronics? Normal 0 false false false EN-US X-NONE X-NONE … Read More
  • Microcontrollers - 8051 Interrupts Microcontrollers - 8051 Interrupts Interrupts are the events that temporarily suspend the main program, pass the control to the external sources and execute their task. It then passes the control to the main program whe… Read More
  • Microcontrollers 8051 Input Output Ports 8051 microcontrollers have 4 I/O ports each of 8-bit, which can be configured as input or output. Hence, total 32 input/output pins allow the microcontroller to be connected with the peripheral devices. Pin configuration,… Read More
  • 555 Timer PWM Audio Amplifier The ubiquitous 555 timer IC handles audio signals in its own pulse-width modulation (PWM) way. Here, the 555 IC works in astable mode. The switching frequency can be varied from 65 kHz to 188 kHz. Selection of PWM frequen… Read More
  • World’s smallest transistor is just 1 nanometer wide For more than a decade, engineers have been eyeing the finish line in the race to shrink the size of components in integrated circuits. They knew that the laws of physics had set a 5-nanometer threshold on the size of transi… Read More

0 comments:

Post a Comment

 
Powered by Blogger