Using the C++ Ternary Operator Like a Rockstar

March 2, 2014

Every C++ programmer should be familiar with the ternary operator. I know there are some camps that will claim it's hard to read and magic syntax, so get over that for this example.

Here's what you've probably seen:

cout << (x > 0) ? "positive" : "negative" << endl;

Maybe you've even seen:

(x > 0) ? cout << "positive" <<  endl : cout << "negative" << endl;

However, did you know you could also use it as an lvalue?

(x < 0 ? x : y) = v;

Or how about this example:

(x < 0 ? x : y)++;

Related Posts

1 Comment

Comment August 21, 2015 by
My absolute favorite: ( x < y ? x : y ) = ( x > y ? y : x );