The Elvis Operator

A new operator was added to the C language in the last revision, one that I don’t cover in my books. (I’m not sure how that happened.) Anyway, it’s the Elvis operator. Unless you’re a fan of the ternary operator, you’ll probably never use it.

As a review, the ternary operator is a delightfully cryptic way to represent a single if-else choice. You can take code such as this:

   if(a > b)
       c = a;
   else
       c = b;

And transform it into this goober:

    c = a > b ? a : b;

In both code snippets, the greater of variables a or b is assigned to variable c.

The ternary operator can’t replace all if-else statements, but it works well in certain situations. In my code, I generally do the if-else structure first and only later reduce it to the ternary operator — but only when such a simplifies the code. It’s rare that I first strive to use the ternary operator.

The ternary operator has its own reduction, known as the Elvis operator: ?: Apparently, enough people think of the ?: characters as an Elvis Presley emoticon, so the operator is given his nickname.

Whereas the ternary operator represents this statement:

result = comparison/text ? if_true : if_false;

The Elvis operator works like this:

result = if_true ?: otherwise;

So the Elvis operator replaces the ternary operator only for specific conditions: When the first statement is true, that value is assigned. Otherwise the second value (or result) is assigned, whether that value is true or not.

Here’s a typical Elvis operator statement:

r = voltage() ?: 120;

The value of variable r is set to the value returned by function voltage(). If the value returned is zero (FALSE), the value 120 is assigned instead. This statement is the equivalent of the following:

    r = voltage();
    if( r == 0)
        r = 120;

In my code, I prefer to use the second set of statements because it’s readable. Still, the Elvis operator is available for those times you feel it’s necessary for obfuscation or it’s cool to use an operator named after a rock-and-roll legend.

Here’s sample code:

#include <stdio.h>

int voltage(void)
{
    return(60);
}

int main()
{
    int r;

    r = voltage() ?: 120;
    printf("Voltage is %d\n",r);

    return(0);
}

Sample run:

Voltage is 60

If you modify the voltage() function to return the value zero, then the output becomes:

Voltage is 120

I’m unsure of the Elvis operator’s origins. In C, it’s implemented as the ternary operator, where the second part is missing. So, effectively:

r = voltage() ?: 120;

is the same as

r = voltage() ? voltage() : 120;

Some programming languages have strict syntax for the Elvis operator, with others using a different set of symbols or logical expressions instead.

Leave a Reply