Conditional Operator (?:) Vs if...else

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.
I find myself using if else more often...although if it's something really simple like if x==4 return true else return false I might use the ? :
What is the conditional Operator? :D

Till now all I used is if..else :D
He's talking about the ternary operator:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <cctype>
#include <iostream>
using namespace 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.

Hope this helps.
Last edited on
Oh That way i choose If...else
:-)
I use ?: where possible. Eg, I prefer

1
2
3
void foo( const char* pStr ) {
    string s( pStr ? pStr : "" );
}
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.
Last edited on
Topic archived. No new replies allowed.