Arduino boolean operators

Hello, I am busy writing a GUI class that has toggle buttons. These buttons can be in one of two states, and thus a boolean is used to save their states. I check if the button is pressed, and then toggle the state boolean. When doing this I noticed that using

boolean state = false;
state != state;

Gave me unexpected results, however

boolean state = false;
state = !state;

Behaves as expected. Below is a simple demo to demonstrate this behavior.

boolean test = false;

void setup() {
  Serial.begin(115200);
  Serial.println(test); //Expected 0 Actual 0
  test != test;
  Serial.println(test); //Expected 1 Actual 0
  test = !test;
  Serial.println(test); //Expected 0 Actual 1
}

void loop() {
  
}

I was just wondering if anyone knows why the first case is not implemented?

state != stateis a comparison, the result of which is ignored.

is a comparison, the result of which is ignored.

Obviously... Thank you :-[.

Otherwise the assignment and comparison would be indistinguishable.

Try exclusive or with 1:

test ^= 1;

edgemoron:
Try exclusive or with 1:

test ^= 1

That's not safe for all booleans. A boolean true is a non-zero value, not 1. It can be one but it might not be. If the value is 7 and you do that, you end up with 6 which is still a true. As far as I know, only negation will guarantee the conversion of any non zero value to a zero.

I stand corrected :blush: again.

state != state

is a comparison, the result of which is ignored.

The “op=” syntax only works for operations have two operands. After all, “A op= B;” is short for “A = A op B;” The only thing surprising about “A != B;” is that it doesn’t result in an error message, which is just C being C (“it’s just fine that you wrote a statement that doesn’t do anything. I’m sure that’s exactly what you meant to do!”)

Try this easy to read, easy to remember method:

state = not state;