Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is void() a valid C++ expression? [duplicate]

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?

like image 495
petiaccja Avatar asked Jan 28 '20 20:01

petiaccja


2 Answers

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.

like image 184
NathanOliver Avatar answered Oct 22 '22 03:10

NathanOliver


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.

like image 34
NutCracker Avatar answered Oct 22 '22 03:10

NutCracker