c++if-statementidioms

Use of ternary operator instead of if-else in C++


I just came across the following (anonymized) C++ code:

auto my_flag = x > threshold;
my_flag ? do_this() : do_that();

is this a standard C++ idiom instead of using if-else:

if (x > threshold)
{
    do_this();
} 
else
{
    do_that();
}

Even though it's only two lines, I had to go back and re-read it to be sure I knew what it was doing.

The marked duplicate doesn't have as good an answer as the selected on here. If it's possible to merge with the duplicate, I'd like to keep this answer over either of the others on the "duplicate".

Note also, my question was about "idiom". The other is "legality". The compiler says it's fine "legally".


Solution

  • No. In general the conditional operator is not a replacement for an if-else.

    The most striking difference is that the last two operands of the conditional operator need to have a common type. Your code does not work eg with:

    std::string do_this() {return {};}
    void do_that() {}
    

    There would be an error because there is no common type for void and std::string:

    <source>: In function 'int main()':
    <source>:15:22: error: third operand to the conditional operator is of type 'void', but the second operand is neither a throw-expression nor of type 'void'
       15 |     my_flag ? do_this() : do_that();
          |               ~~~~~~~^~
    

    Moreover, the conditional operator is often less readable.

    The conditional operator can be used for complicated in-line initialization. For example you cannot write:

     int x = 0;
     int y = 0;
     bool condition = true;
     int& ref;                                 // error: must initialize reference
     if (condition) ref = x; else ref = y;     // and even then, this wouldn't to the right thing
    

    but you can write

     int& ref = condition ? x : y;
    

    My advice is to not use the conditional operator to save some key-strokes compared to an if-else. It is not always equivalent.

    PS: The operator is called "conditional operator". The term "ternary operator" is more general, like unary or binary operator. C++ just happens to have only a single ternary operator (which is the conditional operator).