Alex
Alex

Reputation: 245

What does "void();" as a separate statement mean in C++?

How does this program get compiled fine?

int main() {
    void();  // Does this create a "void" object here?
}

I've tested both under MSVC and GCC. But void is an incomplete type. When you do the same for any other incomplete user-defined type,

class Incomplete;

int main() {
    Incomplete();  // Error saying "Incomplete" is incomplete.
}

Upvotes: 5

Views: 398

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320787

void type is and has always been special. It is indeed incomplete, but it is allowed in many contexts where a complete type is typically expected. Otherwise, for one example, a definition of a void function would be invalid because of incompleteness of void type. It is also possible to write expressions of void type (any call to a void function is an example of such expression).

Even in C language you can use immediate expressions of void type like (void) 0. What you have in your code is just an example of C++-specific syntax that does essentially the same thing: it produces a no-op expression of type void.

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311176

It is allowed construction in C++ that type void could be used as a template argument.

Upvotes: 2

Qaz
Qaz

Reputation: 61970

C++11 §5.2.3 [expr.type.conv]/2 goes into detail (emphasis mine):

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.

It's just a prvalue of type void. No special initialization or anything like int() would have. A prvalue is something like true, or nullptr, or 2. The expression is the equivalent of 2;, but for void instead of int.

Upvotes: 10

Related Questions