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?

Recommended Answers

All 4 Replies

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;
   cin.ignore();
   cin.get();
   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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.