Programming Question

I am a novice at easyC so here is my question.
Why when I am programming my VEX robot using easyC v2 my robot does not respond the same way when

bumper != 0


bumper == 1:

Can some one tell me why?


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.