Go Down

Topic: Equal, not Equal, Double equal.... (Read 3569 times) previous topic - next topic


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

Code: [Select]
if (A == B) {


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

Code: [Select]

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:

Code: [Select]

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:

Code: [Select]

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

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131