Which do you all prefer to use and why? The Conditional Operator or if...else? I typically stick with if...else out of sheer habit even when I have an opportunity to use the operator. For some reason it just bothers me seeing it present in someones code. I think if...else is the way to go for consistency.
#include <cctype>
#include <iostream>
usingnamespace std;
int main()
{
cout << "Please enter A or B> " << flush;
char c;
cin >> c;
cout << (
(toupper( c ) == 'A') // conditional 'if' part
? "You rock!" // 'then' part
: "Nerd!" // 'else' part
) << endl;
return 0;
}
It selects between two options based upon a condition. Unlike if, it can do it inline --meaning that the entire expression resolves to the selected option. In this example, one of two strings.
I use if statements anywhere possible except in a case that makes it much more clear, usually buffering some sort of display string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// like jsmith's example
Something * something( getSomeStuff() );
cout << ( something? something->toString() : "" );
// note that usually its for display on a form or something, not just cout...
// how about displaying TRUE or FALSE
bool asdf;
//...
cout << ( asdf? "TRUE" : "FALSE" );
// or wrapping the output of a single traversal with just one loop
for( ... )
{
cout << item << ( i % COLUMNS? "" : endl );
}
Anyway, the reason that I like this is that often times these outputs are done in great numbers and I can't justify turning 40 lines that fit on the screen into over a hundred just to use the if statement.