Apparently, this ternary expression with void()
as one argument compiles:
void foo() {}
//...
a == b ? foo() : void();
Is void()
a valid expression by the standard, or is it just a compiler thing? If it's valid, then what kind of expression is it?
void()
is a valid expression and yields a prvalue of type void
. In C++ 20 this will be expanded to also include void{}
. The relevant section for this is [expr.type.conv]/2
If the initializer is a parenthesized single expression, the type conversion expression is equivalent to the corresponding cast expression. Otherwise, if the type is
cv void
and the initializer is()
or{}
(after pack expansion, if any), the expression is a prvalue of the specified type that performs no initialization. Otherwise, the expression is a prvalue of the specified type whose result object is direct-initialized with the initializer. If the initializer is a parenthesized optional expression-list, the specified type shall not be an array type.
In addition to other answers, from here:
void - type with an empty set of values. It is an incomplete type that cannot be completed (consequently, objects of type void are disallowed). There are no arrays of void, nor references to void. However, pointers to void and functions returning type void (procedures in other languages) are permitted.
This means that you can initialize your void type to any value a == b ? foo() : void(1)
or a == b ? foo() : void(1111)
but it will perform nothing and would still compile successfully.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With