Categories
c programming tips and tricks

Ternary operators

A ternary operation is one that takes three arguments. In C the ternary operator (?
can be used as a shorthand way of performing if..else tests. The syntax can be expressed like this:

< Test expression > ? < If true, execute this code> : < else execute this code >

For example, given two int variables, t and items I could use if..else to test the value of items and assign its value to t like this:

if (items > 0) {
      t = items;
} else {
      t = -items;
}

Using the ternary operator, I could rewrite that entire code in a single line, like this:

t = items > 0 ? items : -items;
2-3

If you aren’t used to them, ternary operators may look a bit odd, but they can shorten and simplify your code.

Here’s another example. This code displays the first string when there is a single item and the second string when there are multiple items:

if (items == 1) {
      printf("there is %d item\n", t);
} else {
      printf("there are %d items\n", t);
}

This can be rewritten as follows:

printf("there %s %d item%s", t == 1 ? "is" : "are", t, t == 1 ? "\n" : "s\n");

Leave a Reply

Your email address will not be published. Required fields are marked *