In reference to a style difference between Soren and I.
a=b==1?2:3;
b==1?a=2:a=3
huh? Whats that ? doing there?
Ach I don't like ?. If...else.
In reference to a style difference between Soren and I.
I like the 2nd one, its just clearer and I didnt have to look up operator precedence
So much more readable IMO (I don't think I've ever used the : ? ternary operator in code I've written).. and it doesn't take that much more space.Code:if (b==1) a = 2; else a = 3;
I prefer a variation of #1 that is a little more explicit and thus easier to read.
a = ( b == 1 ) ? 2 : 3;
When I choose to use the ternary that is
-Prelude
My best code is written with the delete key.
>So much more readable IMO (I don't think I've ever used the : ? ternary operator in code I've written)
Yes, but it isn't always an option. The ternary operator goes where if/else fears to tread.
>The ternary operator goes where if/else fears to tread.
Care to describe one of those cases? The only time I've seen that the ternary is truly appropriate is for incredibly long expressions; you increase readability and efficiency becuse the expression is only evaluated once as opposed to twice. Aside from that if..else works just fine.
[edit]
I suppose return values and output that use the ternary are okay as well.
[/edit]
-Prelude
My best code is written with the delete key.
for (b=a==1?1:0;b<10;++b) {
cout << "There are " << b << " item" << g==1?"";"s" << " in the box. \n";
}
as opposed to
if (a==1) {
b == 1;
}
else {
b == 0;
}
for (;b<10;++b) {
cout << "There are " << g << " item";
if (g!=1) {
cout << "s";
}
cout << " in the box. \n";
}
I suppose it's mainly a shortcut (ever tried passing a parameter using an if/else to a function). But as Imperito brought this up, would it be possible to implement his code -
using if/elses's without making it harder to read?Code:int a,b,c,d; for(a=1;a<10;++a) { for(b=a==1?2:0;b<10;b++) { for(c=a==1?3:0;c<10;c++) { for(d=a==1?4:0;d<10;d++) { cout<<a<<b<<c<<d; } } } }
I voted the second option. The first is confusing. For a simple if/else, the ternary is no more confusing than for loops instead of while or do-while loops. For loops without all three operands confuse me, but are used often enough. If things get complicated, don't use it.
Wasn't there a contest on the web a while back for the longest functioning for loop?