Three-Way Evaluations

Being traditional and, to be honest, ancient, the C language deals primarily with two-way evaluations: a > b, c != d, r <= 0, and so on. Complex comparisons build upon these atomic nuggets, but among the trendy languages a newer alternative exists: the three-way evaluation.

A two-way evaluation returns a Boolean, 1 or 0 or TRUE or FALSE. A three-way evaluation returns -1, 0, or 1 based on how items compare:

-1 for less than
 0 for equal
+1 for greater than

The C language doesn’t have a three-way operator or other evaluation, but it does have the strcmp() function, upon which this three-way evaluation logic is based: The strcmp() function returns -1, 0, or 1 depending on how two strings compare. When all the characters match, zero is returned. Otherwise -1 or 1 are returned based on how the individual letters compare. A three-way evaluation follows the same logic.

The following code uses the tweval() function to perform a three-way evaluation on two integers.

#include <stdio.h>

int tweval(int a, int b)
{
    if( a<b )
        return(-1);
    if( a>b )
        return(1);
    return(0);
}

int main()
{
    int x,y,r;

    /* get input */
    printf("Enter value 1: ");
    scanf("%d",&x);
    printf("Enter value 2: ");
    scanf("%d",&y);

    /* three-way evaluation */
    r = tweval(x,y);
    if( r<0 )
        printf("%d is less than %d\n",x,y);
    else if( r>0 )
        printf("%d is greater than %d\n",x,y);
    else
        printf("%d and %d are equal\n",x,y);

    return(0);
}

The tweval() function compares a<b and returns -1 if true. It then compares a>b and returns 1 if true. Otherwise, the function returns zero as the two integers must be equal.

Here’s a sample run:

Enter value 1: 5
Enter value 2: 100
5 is less than 100

As is often the case, the C language is capable of emulating a feature offered in a language the cool kids favor, but what it doesn’t have is the common three-way operator, <=>, often called the “spaceship” operator. (The name comes from a text-mode Star Trek game way back when, where the <=> characters represented a spaceship.)

So while you can’t use the a <=> b operator in C, you can concoct your own tweval() or similar function, copying from the strcmp() function — which has been in the C library for decades. And don’t forget to code three-way evaluation functions for other data types: float, double, and char.

Leave a Reply