Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator ?: vs if...else

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

like image 856
Xirdus Avatar asked Aug 25 '10 11:08

Xirdus


People also ask

What is the difference between if-else and ternary operator?

There's a different emphasis: An if / else statement emphasises the branching first and what's to be done is secondary, while a ternary operator emphasises what's to be done over the selection of the values to do it with.

Why use a ternary instead of if-else?

One great time to use the ternary operator instead of the if / else statement is whenever you would otherwise use a simple if / else statement. Anything that can fit in a single line of code is a great time to use the ternary operator because it's much more compact and easy to read.

Which is called ternary operator ?: && ===?

The conditional operator (? :) is a ternary operator (it takes three operands).

Is ternary operator faster than if in C?

It is not faster. There is one difference when you can initialize a constant variable depending on some expression: const int x = (a<b) ?


2 Answers

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.

like image 122
Kirill V. Lyadvinsky Avatar answered Oct 11 '22 16:10

Kirill V. Lyadvinsky


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.

like image 26
ptomato Avatar answered Oct 11 '22 16:10

ptomato