What does void mean in C, C++, and C#? What does void mean in C, C++, and C#? c c

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:

  1. Function argument: int myFunc(void)-- the function takes nothing.

  2. Function return value: void myFunc(int)-- the function returns nothing

  3. Generic 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.


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 absent
  • void f(P) - Return value is absent
  • void *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


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 setup 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 get's to this node it effectively executes:

bar(somedata);

Then in bar you have:

void bar(void* mydata) {    int *data = mydata;    /* do something with data */;}