 # Combining if statments in the same line

I have a clock ticking, and reading the seconds. (0 thru 59)

at 1 and 31 seconds I want an action to occur when I am on page 0. But I wish to make sure the action only runs once each time the 1 or 31 comes around.

Thr following code does NOT work. It will get stuck in the first statement and run 20x times while current_sec = 1 or 31.

``````page = 0;

if ((current_sec == 1 || current_sec == 31) && temp_ready == 0 && page == 0) {
Serial.println("Statement 1");
}
else if (current_sec != 1 || current_sec != 31 && temp_ready == 1 && page == 0) {
Serial.println("Statement 2");
}
``````

But if I split the if statement to the following, It will run correctly.

``````page = 0;
if (current_sec == 1 || current_sec == 31 ) {
if ( temp_ready == 0 && page == 0)  {

Serial.println("Statement 1");
}
}
else if (current_sec != 1 || current_sec != 31 && temp_ready == 1 && page == 0) {
Serial.println("Statement 2");
}
``````

Why am I having issues with combining all the if statements into a single line? Why does it only work when there are 2 if statements nested inside each other?

Or is there a better way to do this action? "When triggered, only run once until reset"

((current_sec == 1 || current_sec == 31) && temp_ready == 0 && page == 0)

( ((current_sec == 1 || current_sec == 31)) && temp_ready == 0 && page == 0)

Both of those suggestions do not solve the issue. It sill will repeat statement 1 20x times until the current_sec changes.

sorry i didn't look at your else if. won't "current_sec != 1 || current_sec != 31" always be true? should it be current_sec != 1 && current_sec != 31?

Yes, learn these: https://en.wikipedia.org/wiki/De_Morgan%27s_laws

eqrunner: Why am I having issues with combining all the if statements into a single line? Why does it only work when there are 2 if statements nested inside each other?

There is no advantage in having them all on one line and I find that nested IF statements are much easier to understand and to debug. This is especially true if there are ELSE clauses.

Code should be written to make it easier for the developer to understand.

...R

gciurpita: sorry i didn't look at your else if. won't "current_sec != 1 || current_sec != 31" always be true? should it be current_sec != 1 && current_sec != 31?

You got a good point there. I should bring out a note pad and write the logic down better. I am thinking that on an Or statement. IF either of them is false, then sounds like the whole statement would no activate. Say time is 31, Page 0, temp ready=0

if ((current_sec == 1 || current_sec == 31) && temp_ready == 0 && page == 0) { then it would be ( False || True) && True && True)

I would think that the current_sec is with in ( ). So as long as one of those statments was true. it would be fine.