SWITCH vs. IF - (your opinion is needed)

Good day all!

I am working on a project that involves the use of a 3 position toggle switch (up=ON1 | middle=OFF| down=ON2) to set the mode of my gizmo. I don't have any code to share since it is currently working just fine but rather I am looking for opinions from folks more experienced then myself (a noob!)

The current setup is very simple, the toggle switch pins connect to two separate pins on the Arduino and I make a programming decision simply by comparing reads (if pin x is HIGH and Pin y is LOW (up position) then Mode 1, --- if pin y is HIGH and Pin x is LOW (down position) then Mode 2 and if both pins x and y are LOW ( (middle position) then Mode 3) - Simple enough but my question is which is "better" to use (eg. what would a more experienced programmer use)

Use IF statements to read the pins and run the code OR read the pins, set the mode and use SWITCH/CASE statements to run the appropriate code?

Thanks

Which ever is more readable to you. I prefer switch/case.

The compiler should be able to create identical code in any case.

It used to be that switch/case was better for large numbers of cases,since it would create a jump table.

I use switch:case to avoid having to do all the tests the if statements require. Seems to me it would run faster.

A switch (X) can only be used where X is an integer type. If you need to classify float values or test strings, or if you need to test more than one thing, then switch isn't going to do it for you.

Switch can also be a bit dangerous because it's a common duffer mistake to leave off the break in a case, leading to consternation and debugging experience building.

At the compiler level, switch implementation usually amounts to a binary tree of comparisons anyhow, unless the range of values is small enough to make a lookup table practical.

gardner:
A switch (X) can only be used where X is an integer type. If you need to classify float values or test strings, or if you need to test more than one thing, then switch isn't going to do it for you.

And a good compiler won't let you

(if pin x is HIGH and Pin y is LOW (up position) then Mode 1, --- if pin y is HIGH and Pin x is LOW (down position) then Mode 2 and if both pins x and y are LOW ( (middle position) then Mode 3)

Mode =( (digitalRead(pinx) << 1) + (digitalRead(piny)) ) ^ 0x03;

And a good compiler won't let you

Well, fortunately, gcc is a good compiler.

Doesn't switch also work on characters, such as received from the Keypad.h library?

case '0':

case 'A':

??

CrossRoads:
Doesn't switch also work on characters, such as received from the Keypad.h library?

case '0':

case 'A':

??

yes it does

Where the data being tested is suitable I prefer switch/case as I find it easier to read. Using if is not too bad as long as each { and } is on its own line and they are used even where there is only one command to be executed if the condition is true, but the code must be properly indented in order for the structure to be seen more easily.

CrossRoads:
Doesn't switch also work on characters, such as received from the Keypad.h library?

Well, char == int, so yes, it does. :wink:

To the OP: I wouldn't worry so much about what is the correct way, at least in terms of compiler performance and whatnot. The machine code differences between a series of if/else statements and switch cases should be minimal, all else being equal. It comes down to style and what you're testing.

As others have said, and I think you understand from how you worded your question, you can't do complex conditionals in a case statement, so you either have to distill the status down to an integer (like you said -- a mode value), or use if statements instead. If you're on equal ground:

mode = <some expression that will ultimately result in values like 0x00, 0x01, or 0x02>;

.. then you get your pick:

switch (mode) {

case 0x00:
    go_thisway();
    break;

case 0x01:
    go_thatway();
    break;

case 0x02:
    go_someotherway();
    break;

default:
    go_away();
    break;
}

IMO, that's neater than this:

if (mode == 0x00) {
    go_thisway();
} else if (mode == 0x01) {
    go_thatway();
} else if (mode == 0x02) {
    go_someotherway();
}  else {
    go_away();
}

especially when you have nested if's, or while () { ... }, or anything else that uses braces. I hate with red-hot passion seeing code like this:

if (condition) {
    if (some_other_condition) {
        if (I_dunno_phase_of_the_moon) {
            while (this_can_still_be_parsed_by_humans) {
                if (anyone_can_debug_this) {
                    go_thisway();
                }
            }
        } else {
            ....
        }
    }
}

I will flip logic tests and otherwise do my very best to write such functions with a return in each conditional so that code after that can be one level un-indented from that mess of braces. God help you if the indentation isn't accurate and you don't have syntax highlighting... Or when the closing brace is pages down from the opening brace. UGH. I'm getting myself angry now. I need a drink....

if (condition) 
{
  if (some_other_condition) 
  {
    if (I_dunno_phase_of_the_moon) 
    {
      while (this_can_still_be_parsed_by_humans) 
      {
        if (anyone_can_debug_this) 
        {
          go_thisway();
        }
      }
    } 
    else 
    {
      ....
    }
  }
}

would be better as the indentation is more obvious even if the closing brace of a code block is on the next page and even the Arduino IDE has matching brace highlighting.

By the way, you forgot to put the triples of braces on the same line to make it really unreadable !

If you application is doing anything useful at all, then this issue is the least of your worries.

It seems to me, if your testing for the various modes involves checking two different things ( i.e. if (( pin1 == high ) && ( pin2 == low ))) then you are better off with the if and else. Note that if the first criterion of an if is false, the computer won't waste time evaluating the second criterion.

Well, char == int, so yes, it does.

sp. "integer"

nested/multiple "if"s are an abomination that should be put down, just sayin' :slight_smile:


Rob

michinyon:
It seems to me, if your testing for the various modes involves checking two different things ( i.e. if (( pin1 == high ) && ( pin2 == low ))) then you are better off with the if and else. Note that if the first criterion of an if is false, the computer won't waste time evaluating the second criterion.

That's why I suggested arriving at the value of Mode algorithmically, rather than messing about with a lot of multiple-condition if statements. It leaves the detection of Mode value to a simple if/else if/else or a switch(). For something with only three possible values, I don't think there's much difference between if and switch, though I lean toward switch for better readability.

UKHeliBob:
(code snip) would be better as the indentation is more obvious even if the closing brace of a code block is on the next page and even the Arduino IDE has matching brace highlighting.

Sure, brace-matching is fairly ubiquitous in code editors, however let's say you're editing a source file with a text editor. Even with (e.g.) vi or nano, while they can have syntax-highlighting plugins, they may not be installed or enabled. OK, that's not an everyday problem, nonetheless it's still relatively frequent in my world. Or, for an example everyone here can relate to, how about posted code on a forum? :wink:

Point being, I see just far too much code with nested if's that really don't need to be. Logic like this, for example:

if (some_condition) {
    ...
    // Long block of code that takes a couple page-downs to go through
    ...
} else {
    a = b;
    c = d + e;
    return 1;
}

... really?? Why not this instead?

if (!some_condition) {
    a = b;
    c = d + e;
    return 1;
}

// The long block of code which no longer needs to be within
// braces at all, goes here....

In this case I didn't bother typing a bunch of nested ifs, but it seems that coders who are unwilling to negate logic to make the flow more concise also have no problem stepping through conditions one at a time and nesting the actual processing code several levels deep. By the time you get to the closing brace of a conditional, you may no longer be able to see the brace the IDE is highlighting for you. :wink: Which is why, when I'm forced to use multi-page braces, I do this (PHP example):

class ThisClass {

    public function read () {
        ....
    } // read()
} // class

UKHeliBob:
By the way, you forgot to put the triples of braces on the same line to make it really unreadable !

Oh my... That's just no good for anybody! :*

AWOL:

Well, char == int, so yes, it does.

sp. "integer"

Yeah, I was using code syntax as a verbal description -- that was sloppy of me. Sorry about that. Being on an Arduino forum, that should've either been explicitly stated as "char is an integer", or "char == uint8_t". (Char is unsigned on AVR, right? I try not to assume that in code, so I don't remember for sure.)

however, character constants are ints so:

size_t x = sizeof('a')

sets x to 2.

KeithRB:
however, character constants are ints so:

size_t x = sizeof('a')

sets x to 2.

Why bother posting such nonsense?

Because I know a lot more about C than C++:
http://c-faq.com/charstring/sizeofchar.html