Skip to main content
GameDev.net gamedev.net
🔒 Locked

statement ? value : value syntax

Started by Omid Ghavami Jan 25, 2006 at 10:30 AM 14 replies 1.6k views
Original Post
Omid Ghavami
Omid Ghavami
Hi! What are your thoughts on using this syntax? Good/Bad code? And how does it get compiled, with say, VC8 compiler? Is this prefered over an if statement where possible or not? Thanks Regards, /Omid
Best regards, Omid
jpetrie
jpetrie
The ?: operator is for the selection of values, not a replacement for an if() statement (i.e., not to control flow). The operator itself is not inherently "bad," but some uses are:
bool test = some_logic();test ? foo() : bar();

That sort of use is generally considered "bad," but
int foo = test ? 100 : 144;

that sort of use is generally considered "okay." Of course, YMMV and whether or not use of the ?: is appropriate in a given scenario is very dependant on the context. As Sneftel says below, readability is the most important thing.

How it gets compiled depends on how its used, but I imagine it will be compiled to very similar machine code as an if() statement (worrying about this is a micro-optimization anyway).
Sneftel
Sneftel
When deciding to use one syntactic feature over another, the first (and possibly only) question you should ask yourself is which will produce more readable code. The compiler is the proper thing to worry about microoptimizations.
Omid Ghavami
Omid Ghavami
Ah thanks for your replies.

I'm guessing readibility is always higher using an if statement, atleast for me.
But code might get a bit bloated if you're doing if else just to increase or decrease a value. But then again this ? : syntax looks so hackish to me and if I would decide I wanted to do more stuff than just alter the value of a variable I'd have to rewrite it.

So I guess I'm going to minimize my use of this syntax.

Thanks for you help!

Regards,
/Omid
Best regards, Omid
haegarr
haegarr
Quote:
Original post by Omid Ghavami
I'm guessing readibility is always higher using an if statement, atleast for me.
But code might get a bit bloated if you're doing if else just to increase or decrease a value. But then again this ? : syntax looks so hackish to me and if I would decide I wanted to do more stuff than just alter the value of a variable I'd have to rewrite it.

I use ?: often. It has some advantages under the right circumstances :)

In C++:

(1) It may increase readability:
// instead ofint a;if(condition)   a = 1;else   a = 2;// IMHO more readableint a = condition ? 1 : 2;

(I think readability is not only a thing of syntax, but also of how may lines of code the eye has to see before recognizing what is coded there.)

(2) It allows to have case-distinction during initializing const vars
const int a = condition ? 1 : 2;
what isn't possible else.

(3) It allows to have case-distinction where statements are not allowed, e.g. in an initialization list (ok, this is just a variation of (2) above):
class B: public A {public:   B(bool condition) : A(condition ? 1 : 2) {}};


I personally prefer the operator over the statement in all cases where it could be applied and the expressions of building the both alternative values aren't too complex.
Omid Ghavami
Omid Ghavami
haegarr:
Thanks for your input! You made some interesting points :)
I shall absorb them.

Regards,
/Omid
Best regards, Omid
Zahlman
Zahlman
Quote:
Original post by haegarr
(I think readability is not only a thing of syntax, but also of how may lines of code the eye has to see before recognizing what is coded there.)


QFE.
Zahlman
Zahlman
Ah, but in context it *has* to be "quoted for emphasis". The point is you need to weigh the time it takes to figure that out versus the time it would take to type/mentally-extract-as-important/read/grok the full phrase. Analogous to making such decisions about the ?: operator :)
Xai
Xai
The single fundamental distinction is that the ?: operator IS an EXPRESSION (or yields an expression at least) and therefore is the appropriate / preferred way to signal that a value will result IN ALL CASES, but its value depends on a simple condition.

int i = isFirstTime ? 0 : lastValue;

but not usually stuff like:

int i = (target == 0 || target.Location.IsNear(source.Location)) ? damageQuotient * 2.0 : minimumSplashDamage;
source.AddDamage(i);

or like:

(i == 0) ? doInitialProcessing() : doNormalProcessing();

The middle example is too complicated for the ?: operator to help readability (and there is not really enough connection between the condition and the result to prefer such a syntax, and also it couldn't grow to cover more cases (which is likely in this type of general logic situation).

The last example is not an expression, so in c++ idioms it is not really used. There is nothing wrong with it, and in a language like ruby people would use things similar to this regularly, but when in rome ...

The first example shows the kind of care where it really shines ... as opposed to:

int i;
if(isFirstTime)
i = 0
else
i = lastValue;

or

int i = 0;
if(isFirstTime)
i = lastValue;

which take more lines, more thought to read, more thought to write, are are slightly more likely to contain bugs (in my opinion).
ApochPiQ
ApochPiQ
I'll throw another vote into the readability ring. I tend to use the ternary operator a lot when it would eliminate code redundancy:

// Ternary good:if(target > current)  current += min(target - current, (current < 0) ? decelerate_factor : accelerate_factor);else  current -= min(current - target, (current > 0) ? decelerate_factor : accelerate_factor);// Without ternary bad:if(target > current){  if(current < 0)    current += min(target - current, decelerate_factor);  else    current += min(target - current, accelerate_factor);}else{  if(current > 0)    current -= min(current - target, decelerate_factor);  else    current -= min(current - target, accelerate_factor);}



I also abuse the operator a lot in PHP for inline variable echoing: is much cleaner looking than
Flimflam
Flimflam
One thing I also note helps readability, is putting parenthesis between the condition argument.
It reads a little better than "whatever = statement ? true : false" aka: "whatever = (statement) ? true : false"
Omid Ghavami
Omid Ghavami
ApochPiQ:

Your example was the very case I was speculating about (slightly altered though) when I decided to ask the question here.

I wanted a value to decrese or increase depending on the value of a statement. However I needed different limit checks for the two cases.

So I had either
if ( isActive ) {    value -= decreaseFactor;    if ( value < lowerLimit ) {        value = lowerLimit;        isActive = false;    }} else if ( value < upperLimit ) {    value += increaseFactor;    if ( value > upperLimit ) {        value = upperLimit;    }}


or

value += isActive? decreaseFactor : increaseFactor;if ( value > upperLimit ) {    value = upperLimit;} else if ( value < lowerLimit ) {    value = lowerLimit;    isActive = false;}


(Might be some syntax or logical errors in the code, since I just wrote it quickly. Only got a short break before the next lecture)

Which of these two would be the better choice in this example?
Or some other way which is better than both? :)

Regards,
/Omid
Best regards, Omid
ApochPiQ
ApochPiQ
The better solution is the one that adheres to your style conventions and is the most clearly expressive. I'd personally favor the second option, but that's not always applicable (some teams have strict guidelines for syntactic style and may frown on the use of the ternary operator).
Xeee
Xeee
well, here's another advantage for the ternary operator over using an ordinary if statement.

you can't do this with an if statement:

const std::string registrationStatus = Registered() ? "Registered" : "Not Registered";


sorry, couldn't come up with a better example, but the point is constness, it's not possible using an ordinary if.

and for me, it's a big advantage coz I like using const when possible.
xee..

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.