Nested ternary operators in C

I started learning C programming back in the late 1980s. I was using the original Microware OS-9 C compiler on a Radio Shack Color Computer 3. It was a K&R compiler, meaning it was the original version of C that was before the ANSI-C standard. Back then, I recall reading a magazine article that claimed C would be “the language of the 80s” so I decided to see what the fuss was about.

A Commodore-using friend of mine, Mark, was helping me learn C. He loaned me a Pocket C reference guide. That, and the Microware documentation, was all I had for reference material. At the time, Mark had moved from his Commodore 64 to a powerful Amiga computer. He would dial in to my OS-9 BBS system and upload source code he wrote on his Amiga and then compile it on my machine to see if it ran there, too. It was amazing that this was even possible, considering how non-portable BASIC programs were from machine to machine.

It was a fun time.

Over the years, I learned much about C from books and friends and just general experimentation. One thing I learned was this weird conditional assignment operation:

a = (b == 10 ? 100 : 200);

It is basically doing this:

condition ? value_if_true : value_if_false

The value of a would be set to 100 if b was 10, otherwise it would be set to 200. It was a shortcut to writing the code like this:

if (b == 10)
{
  a = 100;
}
else
{
  a = 200
}

…or…

switch( b )
{
  case 10:
    a = 100;
    break;
  default:
    a = 200;
    break;
}

I have used this many times over the years, but don’t even know what it’s called. I asked a coworker, and they told me it was a “ternary operator“. Here is the Wikipedia entry on how it works in C:

https://en.wikipedia.org/wiki/%3F:#C

It is a great shortcut for response strings. For instance, turning a boolean true/false result in to a string:

printf( "Status: %s\n", (status == true ? "Enabled" : "Disabled" );

This will print “Status: Enabled” if status==true, or “Status: Disabled” if status==false. What a neat shortcut.

Recently, I saw a nested use of this ternary operator. It never dawned on me that you could do this. It was something like this:

char *colorStr = (value == RED) ? "Red" : (value == BLUE) ? "Blue" : "Unknown";

It was using a second ternary operator for the “value_if_false” condition, allowing it to have three conditions rather than just two. I realized you could nest these in many different ways to create rather complex things… Though, readability would likely suffer. I think I’d just stick with simple if/then or switch/case things for anything more than two choices, but in this case it seemed simple enough.

I thought it was neat, and decided I’d share it here in this quick article.

3 thoughts on “Nested ternary operators in C

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.