Jump to content

  • Log In with Google      Sign In   
  • Create Account

Awesome job so far everyone! Please give us your feedback on how our article efforts are going. We still need more finished articles for our May contest theme: Remake the Classics

C++ Conditional Operator


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
14 replies to this topic

#1 Chad Smith   Members   -  Reputation: 801

Like
0Likes
Like

Posted 16 January 2013 - 11:39 PM

I've always heard and known of the conditional operator in C++ though for some reason my brain would always forget exactly how it's read.  I decided to take a quick look at it again as I do see some places in my code that is a lot longer than it should be just because I always used a full if/else statement to do one quick test. I just wanted to ask to make sure I am reading these right.

 

lets say I have the following:

// assume x has already been declared and defined earlier in the program.
int a = (x > 100) ? 0 : 1;

 

This would read and be the same as:

// again assume x is defined and declared earlier in the program
if(x > 100)
     a = 0;
else
     a = 1;

 

I just want to make sure I am right in reading this.  Even though I do feel dumb that I have always forgot about this operator.

 

So in other words really if the first expression in true, then the second expression is executed.  If the first expression is false then the third expression is executed.  Right?


Edited by Chad Smith, 16 January 2013 - 11:41 PM.


Sponsor:

#2 ultramailman   Members   -  Reputation: 820

Like
0Likes
Like

Posted 16 January 2013 - 11:54 PM

Yes. And the whole thing is one big expression, so it can be used anywhere expressions can be used (right value, function arguments, etc).

#3 L. Spiro   Crossbones+   -  Reputation: 5187

Like
-1Likes
Like

Posted 17 January 2013 - 02:05 AM

I have been corrected.  See below.

 

 

L. Spiro


Edited by L. Spiro, 17 January 2013 - 12:00 PM.

It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

#4 ultramailman   Members   -  Reputation: 820

Like
0Likes
Like

Posted 17 January 2013 - 02:53 AM

It is called the “ternary operator”, in case you want to research it more on Google.  “Conditional operator” is just a common name for it.

 

 

L. Spiro

I think conditional operator is the correct term, and "ternary operator" is a common name for it. "ternary operator" just means the operator takes three operands, like how a "unary operator" takes one (!, -, *, etc), and how a "binary operator" takes two (+, -, *, /, etc).



#5 Álvaro   Members   -  Reputation: 5899

Like
0Likes
Like

Posted 17 January 2013 - 03:03 AM


int a = (x > 100) ? 0 : 1;



I read that as "if x is more than 100, 0; otherwise 1."

While we are at it, that can also be written as
int a = !(x>100);

You may want to read the Wikipedia page on ?:. It has some examples of usage that I find very nice (particularly the `vehicle =' example under `?: in style guidelines'.

#6 Felix Ungman   Members   -  Reputation: 456

Like
0Likes
Like

Posted 17 January 2013 - 03:24 AM

C# also has the null coalesce operator ??.

Foo x = a ?? b;

 

That is, x is assigned a if it's not null, and b otherwise. Reading wikipedia I realize that with GNU extensions, C/C++ also has that operator.

Foo* x = a ?: b;

 

Wow, the more you learn, the more you realize how little you know :)



#7 rip-off   Moderators   -  Reputation: 5066

Like
4Likes
Like

Posted 17 January 2013 - 03:57 AM

While I'm not advocating this as a good idea, the ternary operator is, as ultramailman said, an expression not a statement. This allows for some interesting things don't have a "simple" translation into if/else statements.

 

For example, choosing a variable to assign:

int a = std::rand();
int b = std::rand();
std::cout << "a: " << a << ", b: " << b << '\n';
 
(a > b ? a : b) = 42;
std::cout << "a: " << a << ", b: " << b << '\n';

 

Or even choosing between functions, but calling them with a single set of arguments:

void foo(int x)
{
    std::cout << "Foo: " << x << "\n";
}
 
void bar(int x)
{
    std::cout << "Bar: "<< x << "\n";
}
 
void example(int x)
{
    (x > 100 ? foo : bar)(x);
}

 

To reiterate, just because these are possible does not make them a good idea!



#8 Álvaro   Members   -  Reputation: 5899

Like
2Likes
Like

Posted 17 January 2013 - 07:22 AM

I often use ?: in variable initializations or in return statement, because it's easier to see that I am doing only one thing.
bool ChessBoard::is_in_check(int color) const {
  int king = color == White ? WhiteKing : BlackKing;
  // ...
}



#9 Chad Smith   Members   -  Reputation: 801

Like
0Likes
Like

Posted 17 January 2013 - 09:09 AM

Yea I understand the "just because you can use it doesn't make it right" argument. I don't plan to use it exclusively. Though their were some small areas in my code that just looked weird using a full if/else statement when just initializing a simple variable. After changing some code to it I do seem to like this way better than my if/else statements.

Thanks everyone.

#10 SiCrane   Moderators   -  Reputation: 6672

Like
0Likes
Like

Posted 17 January 2013 - 09:21 AM

I think conditional operator is the correct term, and "ternary operator" is a common name for it.
The term that C++ standard uses for it is conditional operator. See section 5.16 in all of C++98, C++03 and C++11.

#11 rip-off   Moderators   -  Reputation: 5066

Like
0Likes
Like

Posted 17 January 2013 - 09:45 AM

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

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.



#12 ApochPiQ   Moderators   -  Reputation: 7797

Like
1Likes
Like

Posted 17 January 2013 - 11:56 AM

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


#13 BCullis   Members   -  Reputation: 1673

Like
0Likes
Like

Posted 17 January 2013 - 12:30 PM

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
DeviantArt :: Because right-brain needs love too

#14 frob   Moderators   -  Reputation: 7827

Like
0Likes
Like

Posted 17 January 2013 - 12:44 PM

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.



#15 Trienco   Members   -  Reputation: 1307

Like
0Likes
Like

Posted 17 January 2013 - 03:10 PM

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




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS