You cannot declare a void
variable:
void fn() {
void a; // ill-formed
}
Yet this compiles:
void fn() {
void(); // a void object?
}
What does void()
mean? How is it useful? Why is void a;
ill-formed, while void()
OK?
void fn() {
void a = void(); // ill-formed
}
The statement
void();
creates a void value and then discards it. (You can't actually do much with a void value other than discard it or return it.)
The standard† says in 5.2.3 [expr.type.conv
The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, whose value is that produced by value-initializing (8.5) an object of type T; no initialization is done for the void() case
Note that it explictaly calls out that void()
is legal.
† My link is to N4296 which was the last public committee draft before C++14, however the various versions of the standard do not vary here.
Edit
Is it useful? Explicitly like this? No. I can't see a use for it. It is however, useful in template functions which sometimes do something like:
template <typename T>
T foo() {
if (prepare_for_for()) {
return do_foo();
} else {
return T();
}
}
And this will work, even for T
== void
.