In C++, is the ?: operator faster than if()...else statements? Are there any differences between them in compiled code?
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.
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.
The conditional operator (? :) is a ternary operator (it takes three operands).
It is not faster. There is one difference when you can initialize a constant variable depending on some expression: const int x = (a<b) ?
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With