# Switch Function problems

So i actually did this often and it worked before. But somehow i forgot and can't seem to work out whats missing...

Heres the Code

``````boolean Power =  false;

switch (Second)
{

case 0 ... 7:
if (Power = true)
{
Serial.println("Lights OFF");
Power = false;
};
break;

case 8 ... 40:
if (Power = false)
{
Serial.println("Lights On");
Power = true;
};
break;

case 41 ... 59:
if (Power = true)
{
Serial.println("Lights OFF");
Power = false;
};
break;
}
``````

Ive cuz out the rest of the Code cause its not relevant for this Problem. The Numbers are Seconds ranging from 0-59 (being pulled from a RTC and later replaced by Hours).

However the Serial Monitor sends Lights OFF/ON every time

I just want this function to Send the text to the Serial Monitor once it goes from 7 to 8 and from 40 to 41.

In your if statements, = is for assignment, == is for comparison. The if statements use comparison.

From the reference for the if structure:

Beware of accidentally using the single equal sign (e.g. `if (x = 10)` ). The single equal sign is the assignment operator, and sets `x` to 10 (puts the value 10 into the variable `x`). Instead use the double equal sign (e.g. `if (x == 10)` ), which is the comparison operator, and tests whether `x` is equal to 10 or not. The latter statement is only true if `x` equals 10, but the former statement will always be true.

This is because C++ evaluates the statement `if (x=10)` as follows: 10 is assigned to `x` (remember that the single equal sign is the (assignment operator)), so `x` now contains 10. Then the 'if' conditional evaluates 10, which always evaluates to `TRUE`, since any non-zero number evaluates to TRUE. Consequently, `if (x = 10)` will always evaluate to `TRUE`, which is not the desired result when using an 'if' statement. Additionally, the variable `x` will be set to 10, which is also not a desired action.

1 Like

Ithink you are right. I d´not why not work

and all if has = not ==.

RV mineirin

That did the trick! Thanks! ^^

so it would look like this in the end

``````
switch (Second)
{

case 0 ... 7:
if (Power == true)
{
Serial.println("Lights OFF");
Power = false;
};
break;

case 8 ... 40:
if (Power == false)
{
Serial.println("Lights On");
Power = true;
};
break;

case 41 ... 59:
if (Power == true)
{
Serial.println("Lights OFF");
Power = false;
};
break;
}
``````

?

There isn’t a single if statement on that page, correct or not.

So where did you mean to point us at?

a7

@alto777 did you see it?

yep got it fixed now.

Yes, sry, I thought you were saying that the page you linked had that kind of error.

Language peobkem.

a7

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.