-
Notifications
You must be signed in to change notification settings - Fork 21
ternary expression
A ternary expression is a well-known short-hand form of an “if statement”, but in the form of an expression:
a ? b : c
The type of the expression a
must be Boolean
. The implicit type of the expression is the bi-implicit type of the type of expression b
and the type of expression c
.
If the expression a
yields True
, then the expression yields the result of the expression b
. If the expression a
yields False
or short-circuits, then the expression yields the result of the expression c
.
The expression short-circuits if either expression b
or expression c
short-circuits.
Definite assignment rules:
- The VAS before
a
is the VAS before the expression. - The VAS before
b
is the VAST aftera
. - The VAS before
c
is the VASF aftera
joined with the VAS from each short-circuiting point ina
. - The VAS after the expression is the join of the VAS after
b
and the VAS afterc
. - If the type of the expression is
Boolean
, then: -
- The VAST after the expression is the join of the VAST after
b
and the VAST afterc
.
- The VAST after the expression is the join of the VAST after
-
- The VASF after the expression is the join of the VASF after
b
and the VASF afterc
.
- The VASF after the expression is the join of the VASF after
TernaryExpression: OrExpression OrExpression Whitespace ? OrExpression : TernaryExpression
Note the unusual requirement for whitespace before the ?
operator, which differentiates this form of expression from the NotNullExpression. Among other inconveniences, it means that the following style of code popular in C will not compile:
return (flag?1:0)*value;
For purpose of compilation, place a space before the ?
; for readability, it is suggested that spaces precede and follow both the ?
and :
symbols:
return (flag ? 1 : 0) * value;