Equal, not Equal, Double equal....

As a beginner, I am starting to wonder about the use off Equal values.

What is the difference between

A = B or A == B ??????

A = B takes the value from B and puts it into A.

A == B checks to see if A and B have the same value.

So you'd expect to see A = B on a line by itself, but expect to see A == B as part of some other expression like

if (A == B) {
     doSomething();
}

Be careful, though, C/C++ (which the Arduino language is built on), will let you do this:

if (foo = 10) { // Danger!  This assigns 10 to foo.
  // ...
}

which will assign the value 10 to the variable foo, and then check that foo is not zero (which it's not, because it's now 10), and will always execute the thing in the if-statement, not to mention changing the value of foo when you didn't expect it.

Some people prefer to write their comparisons like this:

if (10 == foo) { // compares 10 and foo
  // ...
}

Because if you accidentally write = instead of ==, you'll get an error because you can't assign a value to the constant 10:

if (10 = foo) { // gives a compiler error
  // ...
}
1 Like