Use ternary assignment!

Many languages have a “ternary” (also known as “conditional” ) expression. E.g.,

int foo = (ptr == NULL) ? DEFAULT_VALUE : ptr->a_foo;

In the above, the ternary expression evaluates to DEFAULT_VALUE if ptr is NULL, ptr->a_foo otherwise, and the value of the ternary expression is then assigned to foo.

It is exactly equivalent in outcome to

int foo;
if (ptr == NULL)
    foo = DEFAULT_VALUE;
    foo = ptr->foo;

For my taste, the top version is more clear. Besides avoiding visual clutter, the statement makes it obvious that on the next line of code, foo will have been assigned a value.  That important point is not so apparent in the if-then-else form.

Likewise, a ternary expression can help clarify what a function returns:

return (err_code == 0) ? "GOOD" : "BAD";

Ternary expressions are not an absolute preference. If the Boolean test is unwieldy, then they probably should be avoided. They should not have side effects. Neither am I a fan of cascading ternary assignments.

As always, you should ask “does this improve clarity?”  For me, when considering the use of a ternary, the answer is usually “yes!”.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s