I have seen two types of if/else, which one is faster?
if(a==b) cout<<"a";
else cout<<"b";
OR
a==b ? cout<<"a" : cout<<"b";
I have seen two types of if/else, which one is faster?
if(a==b) cout<<"a";
else cout<<"b";
OR
a==b ? cout<<"a" : cout<<"b";
The ternary conditional is an abuse since it's a mere coincidence that decltype(cout<<"a")
is a type that can be used in a ternary conditional:
cout << (a == b ? "a" : "b");
would be more palatable, and possibly more tractable than the if
, else
, which you should otherwise prefer for its clarity.
And trust your compiler to make the optimisations. checking the output assembly if you have any suspicions.
The performance of either would never be catastrophic for your program.
It all comes down to Code readability.
The tertiary operator has its limitation of only one statement either true or false.