Ternary operator ?: with void return type

Alec Jacobson

October 01, 2013

weblog/

I often like to condense C++ calls into more manageable one-liners with the ternary operator. Suppose I have a function

void foo()
{
  ...
}

And a boolean variable:

bool do_foo;

Then I can replace:

if(do_foo)
{
  foo();
}

with

do_foo?foo():(void)0;

A lot of folks will argue that this is less readable than the original and if I really want it on one line then I should do:

if(do_foo) foo();

or

if(do_foo){ foo();}

But these violate my personal style rules to never use if/else if/else without brackets and brackets always get their own line.

Note: meanwhile I just had the shocking realization that else if is not a single keyword but rather an else without brackets followed by and if block. OK, well, then I guess I'm breaking my rules all the time.