Name
n3905, alx-0030r6 - The Elvis operator ?:
Principles
- Codify existing practice to address evident deficiencies.
Category
Avoid multiple-evaluation isses.
Author
Alejandro Colomar <alx@kernel.org>
Cc: Joseph Myers <josmyers@redhat.com>
Cc: Robert Seacord <rcseacord@gmail.com>
Cc: Aaron Ballman <aaron@aaronballman.com>
History
<https://www.alejandro-colomar.es/src/alx/alx/wg14/alx-0030.git/>
r0 (2025-06-24):
- Initial draft.
r1 (2025-12-01; n3753):
- Use (opt) syntax.
r2 (2026-01-16; n3793):
- wfix.
- Rebase on n3685.
r3 (2026-02-25; n3804):
- Adapt p9.
- Add example.
r6 (2026-06-10; n3905)
- Add CCs.
- s/^Description/Motivation/
- Rebase on n3886.
Motivation
The expression 'x ? x : y' isn't safe within macros: it
evaluates 'x' twice. Some implementations allow omitting the
second operand of this operator, which results in the same
semantics, except that the first operand is not evaluated twice.
Prior art
GNU C.
Proposed wording
Based on N3886.
6.5.16 Conditional operator
@@ Syntax, p1
conditional-expression:
logical-OR-expression
- logical-OR-expression ? expression : conditional-expression
+ logical-OR-expression ? expression(opt) : conditional-expression
@@ Constraints, p5
-If
+If the second operand is specified and
one operand
is a pointer to a variably modified type
and the other operand
is a null pointer constant or has type nullptr_t,
...
@@ Semantics, p6
The first operand is evaluated;
there is a sequence point
between its evaluation
and the evaluation of the second or third operand
-(whichever is evaluated).
+(whichever is evaluated,
+if at all).
+If the second operand is specified,
-The second operand is evaluated
+the second operand is evaluated
only if the first compares unequal to 0;
the third operand is evaluated only if the first compares equal to 0;
the result is the value of the second or third operand
(whichever is evaluated),
converted to the type described subsequently in this subclause.
+If the second operand is not specified,
+the expression behaves
+as if the first operand were also used as the second operand,
+except that it is not evaluated twice.
@@ p9
All array length expressions
that are not an integer constant expression
and which are part of the type
-of the operand
+of an operand
-that is not evaluated
+that is specified and not evaluated
are treated as unspecified lengths
in the determination of type compatibility
and when forming the composite type according to 6.2.7.
@@ p13+1
+EXAMPLE 4
+This operator with an omitted second operand
+can be used for example
+to wrap <b>realloc</b>
+to behave consistently regardless of the system implementation.
+ #define realloc(p, n) realloc(p, (n) ?: 1)