What does void mean in C, C++, and C#?
Basically it means "nothing" or "no type"
There are 3 basic ways that void is used:
Function argument:
int myFunc(void)
-- the function takes nothing.Function return value:
void myFunc(int)
-- the function returns nothingGeneric data pointer:
void* data
-- 'data' is a pointer to data of unknown type, and cannot be dereferenced
Note: the void
in a function argument is optional in C++, so int myFunc()
is exactly the same as int myFunc(void)
, and it is left out completely in C#. It is always required for a return value.
There are two ways to use void:
void foo(void);
or
void *bar(void*);
The first indicates that no argument is being passed or that no argument is being returned.
The second tells the compiler that there is no type associated with the data effectively meaning that the you can't make use of the data pointed to until it is cast to a known type.
For example you will see void*
used a lot when you have an interface which calls a function whose parameters can't be known ahead of time.
For example, in the Linux kernel, when deferring work you will set up a function to be run at a latter time by giving it a pointer to the function to be run and a pointer to the data to be passed to the function:
struct _deferred_work {
sruct list_head mylist;
.worker_func = bar;
.data = somedata;
} deferred_work;
Then a kernel thread goes over a list of deferred work and when it gets to this node it effectively executes:
bar(somedata);
Then in bar you have:
void bar(void* mydata) {
int *data = mydata;
/* Do something with data */;
}
I have always taken it to mean absent. Here are four cases in the C language that matches to this use of absent
R f(void)
- Function parameters are absentvoid f(P)
- Return value is absentvoid *p
- Type of what is pointed to is absent(void) p
- Usage of value is absent
Other C descendants use it for other things. The D programming language uses it for cases where an initializer is absent
T t = void;
- initializing value is absent