Pages: [1]   Go Down
Author Topic: Equal, not Equal, Double equal....  (Read 1122 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 24
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

What is the difference between  

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

Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 11
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
if (A == B) {
     doSomething();
}
Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 9
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
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:
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:
if (10 = foo) { // gives a compiler error
  // ...
}
Logged

Pages: [1]   Go Up
Jump to: