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.
}
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.
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.
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
.
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
.
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