C++ Conditional Operator

Started by
13 comments, last by Trienco 11 years, 3 months ago

Yea I understand the "just because you can use it doesn't make it right" argument.

[/quote]

Don't get my post wrong, I actually quite like the conditional operator, in particular for cases like Álvaro demonstrated.

My post was demonstrating questionable (but interesting) behaviour, hence the caveat.

Advertisement
Here's a mnemonic I use for keeping the conditional operator clear in my head:
IsItTrue ? YesItIs : NoItIsnt

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

In terms of a compiled binary file, is there any difference between ?: and if/else chains? Won't the compiler optimize them both down to the same rough assembly? Or is there a distinct advantage for one of the other in any arena but legibility?

(I've never used it in a clever manner, it just saves me space in a long statement to nest the ?: expression instead of declaring a full if/else block, hence my curiosity)

Hazard Pay :: FPS/RTS in SharpDX (gathering dust, retained for... historical purposes)
DeviantArt :: Because right-brain needs love too (also pretty neglected these days)

In terms of a compiled binary file, is there any difference between ?: and if/else chains? Won't the compiler optimize them both down to the same rough assembly? Or is there a distinct advantage for one of the other in any arena but legibility?

It depends.

Many microprocessors support conditional assignment. On these chipsets the code "x = test ? true : false" can be implemented very cleanly. The compiler may or may not recognize the pattern of assign,if(test){assign}, but the conditional operation makes it clear.

There are many potential ways to optimize if/else chains that depend on exactly how they are used. Again, the individual compiler may or may not recognize them, and may or may not take the optimization.

Generally this is a micro-optimization. Use the conditional operation because it makes your code more maintainable, not because of a potential compiler optimization.

It's a very compiler specific thing, but I vaguely remember an article having a closer look at the resulting code for ?: compared to if/else. One example was that "x = cond ? 5 : 8" would be turned into "x = 5 + cond * 3", while the compiler wasn't able to do the same for the if/else version.

It's far from a good reason to try and use ?: for everything, but a nice example of the kind of thing a modern compiler will do to optimize code (which also makes it a good example of why you as a programmer should not go out of your way to write unreadable code, thinking you can outsmart your compiler when it comes to micro optimizing the small stuff).

f@dzhttp://festini.device-zero.de

This topic is closed to new replies.

Advertisement