Arduino programming guide series

14

The ternary operator

As you become more skilled in programming, you will begin to notice that style matters almost as much as functionality. An element of style in programming is the ability to shrink code without altering its functionality. This results in smaller, more concise programs.

I'll explain with the help of an example.

We often find ourselves writing code like this:

if (digitalRead(9) == HIGH)
     digitalWrite(13, HIGH);
else
     digitalWrite(13,LOW);

An alternative way of writing the same functionality is this:

digitalWrite(13, digitalRead(9) ? HIGH : LOW);

It is shorter, with all functionality included in a single line. Some, might say, it is beautiful.

The short version of the code contains a ternary operator, marked in italics and underlined.

A ternary operator looks like this:

OPERATOR ? TRUE EXPRESSION : FALSE EXPRESSION ;

The OPERATOR contains a regular boolean expression, like "analogRead(0) < 500".

If this expression returns TRUE, then the TRUE EXPRESSION after the "?" delimiter will be executed.

If the OPERATOR returns FALSE, then the FALSE EXPRESSION after the ":" delimiter will be executed.

Ternary operators can make your code shorter, and often reduce the chance of error because they allow for the complete expression to be written in a small amount of space, making it easier to inspect.

Of course, the expression for this particular example can be shortened even further.

Because the digitalRead() function returns a boolean, you can write this:

digitalWrite(13, digitalRead(9));

The example I show here is trivial, and the use of a tertiary operator is not truly necessary. 

But, what if you had a more complicated case?

Let's say that you needed to call an appropriate function depending on the state of digital pin 9. In that case, the ternary operator would be useful and your code would look like this:

digitalRead(9) ? functionA() : functionB();

As you can see, the C language offers quite a few options to help you produce concise (and beautiful) code.

"Arduino programming" series

New to the Arduino?

Arduino Step by Step Getting Started is our most popular course for beginners.

This course is packed with high-quality video, mini-projects, and everything you need to learn Arduino from the ground up. We'll help you get started and at every step with top-notch instruction and our super-helpful course discussion space.

>