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.
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
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');