? : operator

I am having trouble understanding this operator. I read up on it, and from what I see, it has something to do with bool. I have this specific example taken from a guide I am using. int max = x.a < x.b ? x.a : x.b;


If possible, can someone help describe the use of this operator, and help me to understand its usefulness, and possibly what and when it should be used.

Any help would be greatly appreciated.

Thanks, Sabal
It's basically a convenient way to write
1
2
3
4
5
int max;
if (x.a < x.b)
    max = x.a;
else
    max = x.b;

which seems strange for a value called max.
Last edited on
Try reading this tutorial on operators: http://www.cplusplus.com/doc/tutorial/operators.html (scroll to Conditional Operator ) for some examples
the conditional operator is generally used in place of the if....else statements
first the condition to be checked is written followed by the ? (statement to be executed if condition is true) and : (statement to be executed if condition is false);

in your example

int max = (x.a < x.b) ? x.a : x.b;

(x.a<x.b) is the condition to be checked

x.a is executed if condition is true
x.b is executed if condition is false

one of the major differences between if...else statements and the ?: operator is that in if..else
multiple statements can be executed after checking the condition while in ?:
only one statement can be executed
Last edited on
Another difference is that if - else execute blocks, ? : instead returns values
Here's another one: The second and third operands must be evaluate to values of the same type.
For example, you can't do this: std::cout <<(a?"something":'p');
Topic archived. No new replies allowed.