Testing integers for nearness to each other

I'm working on a homework assignment, and one little part has me stuck. I get an 8 character phrase from the user, convert the chars to int pairs based on a telephone keypad, then test the int pairs for nearness to each other. No pair can be closer than 5 to another pair. For instance, 24 28 45 51 is invalid because 24 and 28 are only 4 apart. Here's the part of my code that tests for nearness:

if(abs(one - two <= 4)  || abs(one - three <= 4) ||
   abs(one - four <= 4) || abs(two - three <= 4) ||
   abs(two - four <= 4) || abs(three - four <= 4))
    closePairs = true;

If true, I set a bool. My problem is that it evaluates to true even if there are no pairs too close together! I've run the debugger (VS2012), and this is where the problem happens.

Any thoughts?

Ken Long
closed account (Dy7SLyTq)
try and instead of or
Comparisons always evaluate to 0 or 1; false or true. You are taking the absolute value of a comparison.

|a-b≤4| will always evaluate to 0 or 1.

Perhaps you meant |a-b|≤4 ?
This is what's happening:

Let's assume that 'one' is equal to 1, and 'two' is equal to 5.

abs(one - two <=4)

the expression (two <= 4) is evaluated as false, because 5 is not less or equal to 4.

Which turns the original expression into:

abs(one - 0)

which is:


which is true, because the result of this expression is a non-zero value.
In addition, you're doing the same thing for the other expressions, and the condition is true if any expression is true.

EDIT* Oops
Last edited on
That's not what is happening at all. Subtraction has higher precedence than comparisons.
Thanks everyone. Narrowing the scope of the parenthesis did the trick. It works fine now.

Topic archived. No new replies allowed.