I came across the operator " ? : " in C++ on many occasions, I searched, but I did not find an answer about it, and I am not very clear about its function, for example, this is a fragment in which the operator is:
int conversor(char caracter) {
return ( isdigit(caracter) ? 0 :
(islower(caracter) ? 1 :
(isupper(caracter) ? 2 :
(caracter == ' ') ? 3 : 4)));
}
What is the function of the operator? What does the number followed by the sign "?" mean? ?
Conditional Operator / Ternary Operator
Example
It evaluates its first operand and, if the resulting value is not equal to zero, it evaluates its second operand. Otherwise, it evaluates its third operand, as shown in the following example:
It is equivalent to:
For more information I leave you the following route: https://riptutorial.com/operador_ternario
The operator
? :
, is the ternary operator. Evaluates the expression before the question mark (?
) and if that expression can be interpreted as true, the result will be the expression after the question mark, otherwise the result will be the expression after the colon:
.Conceptually it would behave like this:
If it is Tuesday the thirteenth, it
valor
will containtrue
, since it will evaluate to the expressiondia() == 13
.This is about the general characteristics of the ternary operator, which can be found in dozens of languages such as c , c++ , c# , java , javascript , objective-c , swift , scala , ruby , lua to name a few. Now I am going to mention the special features that the ternary operator has in C++:
Only the conditional branch that is true is evaluated.
The part of the ternary operator that does not hold is not evaluated. So this code:
It will
A1
show for programs without parameters because it only executesa()
, if it executed both it would showAB1
.Works as right and left value.
The ternary operator can be used to the right of an assignment:
Or it can be used on the left of an assignment:
All operands are cast to the same type.
The type of the complete expression of the ternary operator will be the common type of all the types of the expression, therefore:
The type of
a
will bedouble
(which is the common type between1.f
what isfloat
and2.
what isdouble
) while the type ofb
will belong
(which is the common type between3l
what islong
and4u
what isunsigned int
).Note that if a transformation is involved, the expression with the ternary operator cannot be used as the left value:
The ternary operator is not overloadable.
There are only four operators in C++ that cannot be overloaded:
::
..
..*
.?:
.Evaluates the condition given before the ?:, if it is fulfilled, the operation is performed before the ":" or, failing that, the operation that continues the ":" is performed.
It is equivalent to: