What are the benefits of using the Conditional operator (?) over a traditional if/else statement or similar?
Using ? seems to lower readability in some cases but anything else?

9 Years
Discussion Span
Last Post by Richy321

In my book it's just another option. Once you get used to seeing the ? operator it isn't really that problematic. Most often its the fancy operators/conditions within the conditions that make it confuscated for me at least.


You can take advantage of a Ternary statement by doing a comparison and returning a value based on the condition, all on the same line.

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
using std::flush;

const char* result(bool);

int main(){

   int x = 3;
   int y = 4;
   cout << "Is X < Y ? " << result( (x < y) ) << endl;
   int z = (y < x) ? x : y;
   cout << z << endl;
   return 0;

const char* result(bool condition){
    return (condition) ? "TRUE" : "FALSE"; 

I think it's more a matter of style.
I prefer to use if always, but if you have a short condition, with short variable names, go ahead with the ?-syntax(see the example by Alex Edwards above)
Internally I think both are translated to the same branch instructions, so it will never be a question of performance.


As long as there is no performance hit that i'll get picked up on i'll carry on using them.
Thanks for ya help people.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.