View Single Post
  #2   Spotlight this post!  
Unread 11-12-2008, 09:58
AndrewN's Avatar
AndrewN AndrewN is offline
it's alive!
AKA: Andrew Nicholson
FRC #1778 (Chill Out)
Team Role: Mentor
 
Join Date: Jan 2007
Rookie Year: 2006
Location: Edmonds, WA
Posts: 48
AndrewN is just really niceAndrewN is just really niceAndrewN is just really niceAndrewN is just really niceAndrewN is just really nice
Re: Programming Question

C has a number of tests for comparing two numerical values:
== tests if the two values are exactly equal
!= tests if the two values are not equal

So the expression (bumper != 0) literally means "the value of bumper does not equal zero", it could be any value at all, other than zero, i.e. bumper could contain 3 and this expression would be true.

Where as the expression (bumper == 1) literally means "bumper is exactly 1". In the above example if bumper were 3 this would be false.

So for the values of bumper equal to 0 and 1, the two expressions are equivalent. For all other values they are not equivalent expressions.

In C when an expression is being used as a boolean value (true/false) the numerical value of 0 is treated as false. All other numbers are treated as true.

Aside: until recently C had no real boolean type.

You can use the operator ! to invert a boolean value.

So the expression ((!1) == 0) is always true, where as ((!0) == 1) is not necessarily true in all compilers, but is true in easyC.

If you are treating "bumper" as a boolean value then the expressions:

(!bumper) is a better test to check if bumper is false, and
(bumper) is a better test to check if it is true

instead of testing for equality against 0 and 1. These expressions clearly indicate that you wish to treat "bumper" as a boolean and you won't make any mistakes.

Hint: Be very careful about not using a single "=" where you should have used a "==". The "=" will set the value of bumper to what you thought you were testing against instead of not changing it. Get into the habit of writing "if (3 == myValue) { ... }" instead of "if (myValue == 3) { ... }" that way if you miss the second "=" the compiler will generate an error instead of silently doing an assignment.

Cheers!
__________________
Andrew Nicholson
2011 FRC Robot Inspector (Seattle, Portland)
Mentor FRC 1778 "Chill Out", FTC 3018, 3940 "Hawks", 4434 "Heat Misers"

"Everything should be made as simple as possible, but no simpler."