views:

571

answers:

8

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

+23  A: 

Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.

ptomato
+1 For many applications, the perf difference is not worth considering even on a really dump compiler.
delnan
Regarding maintainability of code I'd prefer if...else. At least for me it is easier to read.
Exa
@Exa: Depends on the context. The ternary operator is often better when you are initializing an object.
Nemanja Trifunovic
@Nemanja: That's why I said "At least for me". I was just referring to the readability of code :)
Exa
May I please ask, HOW is a conditional less maintainable than an "if"?If you have two equal options, consistently choosing the slower one is premature pessimization.
kotlinski
@kotlinski, I'm not saying a conditional is less maintainable than an if. They are both clearer in certain, differing, circumstances, as described in the answers of the _To ternary or not to ternary_ question linked above.
ptomato
A: 

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

Alex Farber
-1: On what version of what compiler, on what platform, with what code?
DeadMG
DeadMG: VB6 compiler, obviously!
Alex Farber
+19  A: 

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.

Kirill V. Lyadvinsky
Yep, with "if-else" first initialization with some default value then assignment of a new value. A few more processor cycles spent.
Developer Art
@Developer Art: Which isn't possible with a `const` variable.
Job
You could create a non-const variable, assign to it in the if/else, then create a new const variable and construct it with the non-const. Rather wasteful, but far from impossible.
DeadMG
@DeadMG, in the end you will get one more variable in the same scope, which <strike>could</strike>will be confusing. This is not the same.
Kirill V. Lyadvinsky
I said that it was wasteful. You've given just one example of a way in which it is a waste. But it's absolutely not impossible.
DeadMG
What about when initializing a const member?
UncleBens
Good that lambdas will "solve" this for if/else :) haha
Johannes Schaub - litb
@DeadMG: You cannot write an Integral Constant Expression with `if/else`, but you can with `?:` . That is the real difference. Practical: `char foo[ a < b ? b : a ];` cannot be rewritten with if/else; the declarations would end up in the wrong scopes.
MSalters
Nor can it be written with ?:, because [] needs to be not just const but constexpr, which the result of ?: isn't, unless both a and b are constexprs, in which case, ?: won't compile to any machine code. Edit: There's also alloca, the argument of which is runtime.
DeadMG
+7  A: 

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.

James Curran
Doesn't even need a ternary operator: `printf("Total: %d item%s", cnt, "s" + (cnt==1));`
MSalters
+8  A: 

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".

jalf
+1. When I was developing for PS3 using GCC, using conditionals instead of "if" was useful to avoid branches.
kotlinski
+1  A: 

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

Proclyon
first line should probably read `int x = x == 1 ? 1 : 2` or possibly `int x = (x == 1) ? 1 : 2`
Hasturkun
My point was merely to show the view of the code, the cleanlyness of one line is nice yes. But if you want to see CONDITION / ASSIGNEMENT the content of the code can be bogus. If you want to spot what is what you look at the operator and the location alone.I see the word IF and ( ) I know , ah , that is a condition. I see A = B ? CONDITION : CONDITION did you immedeatly spot that for yourself? Most people I know that program do not, maybe it's because most people I know that program are rookies like me.You are correct ofc in the numbers being nonsense, thats the point.
Proclyon
First line definitely needs some parentheses. Perhaps "int x = (y==1) ? 0 : 1;" or "int x = ((y==1) ? 0 : 1);"
supercat
I'm sorry, but I have no problem seeing the assignment. If you choose to overcomplicate the example to make your point, that's your problem. Why don't you write `x = x = 1;` everywhere and then complain that assignment is too complicated and should be avoided.
UncleBens
A: 

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.

supercat
A: 

Hi,

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.

ksrao