As explained, for example, here, there are 3 main uses for the void keyword (more experienced C/C++ programmers can skip to the 4th use):
1) As a return type for function that doesn’t return anything. This
will cause a code sample like this:
void foo();
int i = foo();
to generate a compiler error.
2) As the only parameter in a function’s parameter list. AFAIK, an empty function’s parameter list is exactly the same to the compiler and therefore the following 2 lines are identical in meaning:
(edit: it is only true in c++. The comments show the difference in c).
int foo();
int foo(void);
3) void* is a special type of generic pointer– it can point to any variable that is not declared with the const or volatile keyword, convert to/from any type of data pointer, and point to all non-member functions. In addition, it cannot be dereferenced. I will not give examples.
There is also a 4th use that I don’t fully understand:
4) In conditional compilation it is often used in the expression (void)0 as following:
// procedure that actually prints error message
void _assert(char* file, int line, char* test);
#ifdef NDEBUG
#define assert(e) ((void)0)
#else
#define assert(e) \
((e) ? (void)0 : \
__assert(__FILE__, __LINE__, #e))
#endif
I’m trying to understand the behavior of this expression through experiments. All the following are valid (compile well):
int foo(); // some function declaration
int (*fooPtr)(); // function pointer
void(foo);
void(fooPtr);
void(0);
(void)0;
void('a');
void("blabla");
exampleClass e; //some class named exampleClass with a default ctor
void(e);
static_cast<void>(e);
but these are not:
void(0) // no semicolon
int i = void(0);
Can I conclude from this that “void” (in the context of the 4th use) is simply a special type that any type can cast to it (whether it is c-style or cpp-style), and it can never be used as an lvalue or rvalue?
James McNellis pointed out in a comment above that
voidcan be used as an rvalue via the expressionvoid().He quoted this from the current C++ standard:
This makes it possible to write code like …
and use
foo<void>()(most likely from other templated code, I would imagine).Formally
voidis just an incomplete type that can never be completed.