Comparing Three Items

Logic can be frustrating, especially for non-Vulcans. The computer is kind of a Vulcan, so logic comes naturally to the machine. Programming languages are packed with logical expressions. A programmer’s duty is to convert human thoughts into the raw, powerful logic the computer understands — and end up with the desired result.

As a case in point, I recently wrote code that required me to compare three variables: a, b, and c. Were they equal to each other? For some reason, this process caused me a massive brain cramp.

As a review, when two variables are equal, the comparison is made like this:

(a == b)

That portion of a statement evaluates either TRUE or FALSE. This is basic logic, and as long as you remember to use two equal signs instead of one in C, you’re gold.

Now stir variable c into the mix:

(a == b)
(b == c)
(a == c)

All three statements must be TRUE if the three variables are identical, but you don’t need to code all three. You can, but it’s unimpressive.

Using the transitive property, you know that if a == b and a == c then b == c. Therefore, only two comparisons are needed:


(a == b)
(a == c)

In C, you could code such as comparison as:

if( a == b && a == c )

The program compares variables a and b and gets the result, TRUE or FALSE. Then it compares b and c and gets the result, TRUE or FALSE. Then it compares those two results: TRUE && TRUE is what you need to see if all variables are equal to each other; TRUE && TRUE evaluates to TRUE.

Here’s sample code:

#include <stdio.h>

int main()
{
    int a,b,c;

    a=10; b=10; c=10;

    if( a == b && a == c )
        puts("The variables are equal to each other");
    else
        puts("The variables are not equal to each other");

    return(0);
}

Then I thought of a brilliant shortcut:

if( a == b == c )

So I modified the code. Here’s the output:

The variables are not equal to each other

This mistake is common in programming, mostly because the programmer tries to over-apply logic.

Following the order of precedence, variable a is compared with variable b and the result is generated, TRUE or FALSE. Then that result is compared with variable c, as in:

if(TRUE == c)

Or:

if(FALSE == c)

Odds are good that’s not the comparison you wanted. It works with values 0 and 1 — and I’ve used that trick in my code — but it doesn’t work with other values, such as 10 in the sample program.

The bottom line is that when you need to compare three values, you can get by with only two comparisons. Put them into a single statement and use the logical && to connect them: ( a == b && a == c )

Leave a Reply