Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.
}
like image 432
Alex Avatar asked Sep 14 '14 16:09

Alex


People also ask

What is void statement in C?

Void functions are stand-alone statements In computer programming, when void is used as a function return type, it indicates that the function does not return a value. When void appears in a pointer declaration, it specifies that the pointer is universal.

What does void main void mean in C?

void main ( ) is the first execution part of a program in a programming language that have bottom -top approach. here, void mean empty. void function doesn't return any value. by default, it return int value. you can also define return statement.


2 Answers

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.

like image 64
chris Avatar answered Sep 28 '22 07:09

chris


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.

like image 28
AnT Avatar answered Sep 28 '22 08:09

AnT