A bit help on a logic function

Hello guys,
I wrote this function which follows the following logic.

void switchAction(boolean action, boolean switching) {

if ((action==1) && (switching==1)) { ON(); } 
if ((action==1) && (switching==0)) { OFF(); } 
if ((action==0) && (switching==1)) { OFF(); }
if ((action==0) && (switching==0)) { ON(); }
 
}

I'm not a wiring expert, but I'm sure it's easier to write it.
Could you give me a suggestion?

Thank you

if (action == switching)
  {
    ON();
  }
else
  {
    OFF();
  }

This is a programming problem so I have suggested to the Moderator to move it to the Programming section.

If what you have works and you find it easy to understand then why change it?.

...R

Thanks so much!

Hi,
Does it work?
If so then it looks an extremely tight piece of code.

You could make it bigger using switch..case function, but why?

Tom... :slight_smile:

Tight:

void switchAction(boolean action, boolean switching) {
action ^ switching ? OFF() : ON(); // action exclusive or switching
}

JCA34F:
Tight:

And impenetrable for a newbie, perhaps?

...R

Probably, but if they don't learn things like this, they'll always be newbies. :slight_smile:

Hi,
The biggest hassle with this sort of abbreviated code is it may scare some noobs away.
I don't code like that, I had to go looking to check how to fully interpret it.

I prefer my code to be self explanatory as possible, so a one line If statement doesn't do that readily in my opinion.
Does the shorter code compile to any smaller assembly code?

Tom.. :slight_smile:

JCA34F:
Probably, but if they don't learn things like this, they'll always be newbies. :slight_smile:

Nonsense: sometimes doing things the "long" way is the "right" way.

Most of the time, writing code like that is just to show others that you know how. It serves no purpose whatsoever in making the code readable (on the contrary, in fact) and probably makes it no quicker or smaller.