Is void a data type in C?
Is void
a data type in the C programming language? If so, what type of values can it store? If we have int
, float
, char
, etc., to store values, why is void
needed? And what is the range of void?
Void is considered a data type (for organizational purposes), but it is basically a keyword to use as a placeholder where you would put a data type, to represent "no data".
Hence, you can declare a routine which does not return a value as:
void MyRoutine();
But, you cannot declare a variable like this:
void bad_variable;
However, when used as a pointer, then it has a different meaning:
void* vague_pointer;
This declares a pointer, but without specifying which data type it is pointing to.
Yes, void
is a type. Whether it's a data type depends on how you define that term; the C standard doesn't.
The standard does define the term "object type". In C99 and earlier; void
is not an object type; in C11, it is. In all versions of the standard, void
is an incomplete type. What changed in C11 is that incomplete types are now a subset of object types; this is just a change in terminology. (The other kind of type is a function type.)
C99 6.2.6 paragraph 19 says:
The void type comprises an empty set of values; it is an incomplete type that cannot be completed.
The C11 standard changes the wording slightly:
The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.
This reflects C11's change in the definition of "object type" to include incomplete types; it doesn't really change anything about the nature of type void
.
The void
keyword can also be used in some other contexts:
As the only parameter type in a function prototype, as in
int func(void)
, it indicates that the function has no parameters. (C++ uses empty parentheses for this, but they mean something else in C.)As the return type of a function, as in
void func(int n)
, it indicates that the function returns no result.void*
is a pointer type that doesn't specify what it points to.
In principle, all of these uses refer to the type void
, but you can also think of them as just special syntax that happens to use the same keyword.