Im looking for an example of using switch case to replace boolean or if statements. Instead of if pin one is high do this if pin two is high do something else. I think it could be done with switch cases. Am I correct?
A switch statement is nothing more than a cascaded if/elseif/else statement block in shorthand notation. It will not allow you to switch on anything single discrete values like byte, int, short, long. Floats, doubles, strings and the like will not work. Most good compilers implement the switch statement as a lookup table of jump addresses.
The basic syntax looks like:
switch (variable) {
case 1:
do something
do something
break;
case 2:
do something
do something
break;
default:
do something
break;
}
The values in the case statements do not need to be consecutive. The code after the case statement and before the break can be as complex as you want including other switches, conditionals, loops, …
If you forget a break, the current case will get executed and then the following one will as well. The so called fallthrough is a classic bug that is often warned about in a good compiler but SOMETIMES has its uses.
Variable in the switch statement can be a complex expression as long as it evaluates to a integer type number.
Someone should put a book on C/C++ on their birthday list!
Actually, if/else if logic sounds better for your application.
switch case is more for something like this:
switch color
case RED
/* do red stuff */
break
case BLUE
/* do blue stuff */
break
…
Thank you very much!!