[c++] Ternary operator ?: vs if...else

In C++, is the ?: operator faster than if()...else statements? Are there any differences between them in compiled code?

This question is related to c++ performance conditional-operator

The answer is


I've seen GCC turn the conditional operator into cmov (conditional move) instructions, while turning if statements into branches, which meant in our case, the code was faster when using the conditional operator. But that was a couple of years ago, and most likely today, both would compile to the same code.

There's no guarantee that they'll compile to the same code. If you need the performance then, as always, measure. And when you've measured and found out that 1. your code is too slow, and 2. it is this particular chunk of code that is the culprit, then study the assembly code generated by the compiler and check for yourself what is happening.

Don't trust golden rules like "the compiler will always generate more efficient code if I use the conditional operator".


During reversing some code (which I don't remember, few years ago) I saw single line difference between the Machine Code of :? and if-else. Don't remember much but it is clear that implementation of both is different.

But I advise You to not choose one of them b'coz of its efficiency, choose according to readability of code or your convenience. Happy Coding


In C A ternary operator " ? : " is available to construct conditional expressions of the form

exp1 ? exp2:exp3

where exp1,exp2 and exp3 are expressions

for Example

        a=20;
        b=25;
        x=(a>b)?a:b;

        in the above example x value will be assigned to b;

This can be written using if..else statement as follows

            if (a>b)
             x=a;
             else
             x=b;

**Hence there is no difference between these two. This for the programmer to write easily, but for compiler both are same.*


I think that there are situations where the inline if can yield "faster" code because of the scope it works at. Object creation and destruction can be costly so consider the follow scenario :

class A{
    public:
    A() : value(0) {
        cout << "Default ctor" << endl;
    }
    A(int myInt) : value(myInt)
    {
        cout << "Overloaded ctor" << endl;
    }

    A& operator=(const A& other){
        cout << "= operator" << endl;
        value = other.value; 
    }

    ~A(){
        cout << "destroyed" << std::endl;
    }

    int value;

};


int main()
{
   {
       A a;
       if(true){
           a = A(5);
       }else{
           a = A(10);
       }
   }

   cout << "Next test" << endl;
   {
        A b = true? A(5) : A(10);
   }
   return 0;
}

With this code, the output will be :

Default ctor                                                                                                                                                                                                                      
Overloaded ctor                                                                                                                                                                                                                   
= operator                                                                                                                                                                                                                        
destroyed                                                                                                                                                                                                                         
destroyed                                                                                                                                                                                                                         
Next test                                                                                                                                                                                                                         
Overloaded ctor                                                                                                                                                                                                                   
destroyed  

So by inlining the if, we save a bunch of operation needed to keep a alive at the same scope as b. While it is highly probable that the condition evaluation speed is pretty equal in both scenarios, changing scope forces you to take other factors into consideration that the inline if allows you to avoid.


They are the same, however, the ternary operator can be used in places where it is difficult to use a if/else:

printf("Total: %d item%s", cnt, cnt != 1 ? "s" : "");

Doing that statement with an if/else, would generate a very different compiled code.


Update after 8 years...

Actually, I think this would be better:

printf(cnt == 1 ? "Total: %d item" : "Total: %d items", cnt);

(actually, I'm pretty sure you can replace the "%d" in the first string with "one")


Regardless the compiled code, They are semantically different thing. <cond>?<true expr>:<false expr> is an expression and if..else.. is a statement.

Although the syntax of conditional expression seems awkward, it is a good thing. You are forced to provide a <false expr> and the two expressions are type checked.

The equivalent to if..else.. in expression-based, functional language like Lisp, Haskell is ? : in C++, instead of if..else.. statement.


You are not forced to put it all on one line:-

x = y==1 ?
    2
    :// else
    3;

It is much clearer than if/else because you can see immediately that both branches lead to x being assigned to.


No, they are converted to exactly the same executable code.


It is not faster. There is one difference when you can initialize a constant variable depending on some expression:

const int x = (a<b) ? b : a;

You can't do the same with if-else.


I would expect that on most compilers and target platforms, there will be cases where "if" is faster and cases where ?: is faster. There will also be cases where one form is more or less compact than the other. Which cases favor one form or the other will vary between compilers and platforms. If you're writing performance-critical code on an embedded micro, look at what the compiler is generating in each case and see which is better. On a "mainstream" PC, because of caching issues, the only way to see which is better is to benchmark both forms in something resembling the real application.


Now I can't help you with that, I may be able to help with a secondary question beneath it, do I want to use it? If you just want to know of the speed, just ignore my comment.

All I can say is please be very smart about when to use the ternary ? : operator. It can be a blessing as much as a curse for readability.

Ask yourself if you find this easier to read before using it

int x = x == 1 ? x = 1 : x = 1;

if (x == 1)
{
   x = 1
}
else
{
   x = 2
}

if (x == 1)
    x = 1
else
    x = 1

Yes It looks stupid to make the code 100% bogus. But that little trick helped me analyse my readability of code. It's the readability of the operator you look at in this sample, and not the content.

It LOOKS clean, but so does the average toilet seat and doorknob

In my experience, which is limited, I have seen very little people actually being able to quickly extradite information required from a ternary operator, avoid unless 100% sure it's better. It's a pain to fix when it's bugged aswell I think


Ternary Operator always returns a value. So in situation when you want some output value from result and there are only 2 conditions always better to use ternary operator. Use if-else if any of the above mentioned conditions are not true.


Just to be a bit left handed...

x ? y : x = value

will assign value to y if x is not 0 (false).


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder

Examples related to conditional-operator

Ternary operator in PowerShell Javascript one line If...else...else if statement How to do one-liner if else statement? What is the idiomatic Go equivalent of C's ternary operator? bash "if [ false ];" returns true instead of false -- why? One-line list comprehension: if-else variants Kotlin Ternary Conditional Operator Conditional statement in a one line lambda function in python? ORACLE IIF Statement Twig ternary operator, Shorthand if-then-else