r/C_Programming • u/Stickhtot • Jul 29 '26
Discussion What exactly is void?
In a function definition, void basically means that it doesn't return a type value, yet in on itself it is it's own type? Looking at several pieces of code it looks like that it's used to be able to be more "flexible"
Don't know what else to add here, though I'm more on looking for examples and explanations of why the void type is used
70
Upvotes
53
u/Innowise_ Jul 29 '26
void basically means “no value.” In void f(void), the first void means the function returns no value, while the second means it takes no arguments. void * is a separate use: it can hold a pointer to any object type, but it has to be converted to the correct pointer type before dereferencing.
129
u/aioeu Jul 29 '26 edited Jul 29 '26
Be aware that C is rather notorious for reusing keywords to mean multiple different things. I think there's something like four distinct meanings for the
statickeyword...21
u/Snarwin Jul 29 '26
voidis a placeholder that's used when C's syntax requires a type, but there's no real type that would be correct to use in that context.For example: C's function declaration syntax requires you to write the return type of the function. What do you write if the function doesn't return anything?
void.Or, C's syntax for pointers requires you to specify the type of the value being pointed to. What do you write for the pointer you get from
malloc, which points to unused memory without any values stored in it?void*.27
u/TheThiefMaster Jul 29 '26
"void" means "nothing", but "void*" doesn't mean "pointer to nothing" it means "pointer to anything". C has lots of cases of double-use of keywords like this.
5
u/Longjumping_Cap_3673 Jul 29 '26 edited Jul 30 '26
From a type theory perpective,
voidin C is a degenerate unit type.Conceptually, a unit type has one value, not none. Since there's only one value of a unit type, the value can be automatically produced whenever it is needed. Also, since the value can be produced, it doesn't take up any space to "store" a value, since it doesn't need to be stored. A function with return type unit doesn't need an explicit return, because there's only one possible value it can return. Passing a unit value to a function is like passing nothing, since it's size zero and the function could produce the value itself anyway. A pointer to unit isn't special, except that it has no alignment requirements, so it's convenient for substituting as the type of any other pointer.
But C's
voidwas created before this formalism, so it doesn't have all the properties it could. For example, C doesn't let you ever bind a value of type void to a variable.3
u/primitiveblob Jul 29 '26
void in function return- no return type
you may be thinking of void as pointers. true, they dont have a type, so they can be pointed to wherever. but you have to cast them to a type first. so void * is often used to store a pointer to something, you just dont know what yet. but if you wish to use the data, you have to cast it to a type first
3
u/DawnOnTheEdge Jul 29 '26 edited Jul 29 '26
To get langauge-lawyery: The
voidkeyword has several different meanings in context, which other languages spell distinctly.intreturn value just because early C required one.()already meant something else in C.void*is a generic pointer, and in this contextvoidbehaves a lot like a top type. Early C had no generics, but was weakly-enough typed that passing any kind of pointer to a function likememcpy()would work. For binary compatibility with that legacy code, avoid*is still required to have the same object representation as achar*orunsigned char*.void*. Since these are always converted to another pointer type immediately, C lets you do that without a cast. (But C++, which wanted to get programmers to switch tonew, does not,)NULLas((void*)0). The POSIX standard requires this definition, but C++ does not permit it becauseint *p = ((void*)0);is illegal in C++. Microsoft Windows definesHULLas0, which breaksprintf("%p", NULL)on 64-bit Windows. Defining it as0Lor0LLas appropriate would solve both these problems but unexpectedly allow integer arithmetic onNULL. Most modern compilers create a special keyword for it. The replacement,nullptr, is a unit type with special implicit conversions.?operator tovoidto get them to match as expressions, like a bottom type. Some tools, likelint, also issued warnings if any return value was implicitly ignored, so to shut it up you had to write eitherif (printf("hello, world!\n") != HELLO_LEN)or(void)printf("hello, world!\n");.2
u/tstanisl Jul 29 '26 edited Jul 29 '26
This is a special type which has no value. Any object type can be cast to void (i.e.
(void)1,(void)"123") which basically means explicitly discarding the compute value. Next, a pointer to any object type can be cast to a pointer tovoid. However, thevoidis an incomplete type thus one cannot create a variable ofvoidtype. Therefore declarations likevoid a;will cause compilation failure.2
u/Key_River7180 Jul 29 '26
void means no value, but there is void*, void* means void pointer, it is a generic pointer that conveys no type information. so you need to cast it to another pointer type to use it.
2
u/Afraid-Locksmith6566 Jul 29 '26
void has 2 meanings.
as a return type: nothing is being returned from a function
as a pointer type (void*): this type has no specified representation
2
u/NotThatJonSmith Jul 29 '26
https://thecodelesscode.com/case/5
2
u/HildartheDorf Jul 29 '26
voidhas multiple meanings.As a return type, it means "This function doesn't return a value" or more theoretically "This function returns The Unit Type".
As a pointer type it means "pointer to an unknown type" (or more theoretically "The Top Type").
From a purely theoretical type of view, these are completey opposite meanings. One is a type carrying no information, the other is a type potentially containing any other type.
2
u/burlingk Jul 29 '26
void is not a type so much as a lack of type.
This lets it do double duty as a kind of "generic" type. But it's on you (the developer) to keep up with the math involved.
A void pointer can be allocated to hold the right amount of memory for the type(s) you want it to hold. Then when you use it, you make sure the data is able to function as the type you want it to act like.
The result is that you can do a lot of powerful stuff in a language that doesn't technically have generics, but if it backfires it's on you.
C doesn't give you a lot of tools to make sure it's actually what you want it to be (after all you told C it was void), but there are different techniques.
2
u/SyntheticDuckFlavour Jul 30 '26 edited Jul 30 '26
Instead of looking at whether
voidshould be treated as a type, a better interpretation is to viewvoidas a place-holder to indicate the absence of something. Used on its own indicates the absence of a data type (and consequently the absence of a value) when present as part of a function return syntax, and/or the argument syntax.void*means absence of a type associated with a memory address.3
u/Atijohn Jul 29 '26
There's
void, and then there'svoid *.voidisn't really used outside of function return types, you can cast an expression to it like(void)0, which is sometimes used inside macros to make sure the expression the macro evaluates to doesn't get used outside of it.void *is a special kind of pointer that can point at anything and it can be implicitly cast to any other pointer without a compiler warning. You typically see it in library code where it's used to pass through pointers to data of a type the library code doesn't know about.2
u/Mognakor Jul 29 '26
Gonna use a slightly different metaphor.
voidindicates an invalid operation.void f(x)It is invalid to return a value or trying to use the "returned" value.int f(void)It is invalid to pass a value to the methodvoid * xIt is invalid to dereference the pointer1
u/GhostVlvin Jul 29 '26
There are few cases where void is used
1
u/SmokeMuch7356 Jul 29 '26 edited Jul 29 '26
voidis a type with no values and no size. It is an incomplete type that cannot be completed, so you can't declare anyvoidvariables. However, since you can declare pointers to incomplete types, you can declare pointers tovoid:More on that later.
A
voidexpression is only evaluated for its side effects; you can't assign the result of avoidexpression to anything, nor can avoidexpression be the target of an assignment.It was introduced in C89 to provide a return type for functions that were only executed for their side effects (what would be called "procedures" in languages like Fortran or Ada). In K&R C there was no good way to indicate that, and a convention developed that such functions wouldn't be explicitly typed:
and not have a
returnstatement.In K&R and C89, functions that weren't explicitly typed were assumed to return
int.Unfortunately, that meant you could write code like
and the compiler couldn't warn you that
sortdidn't return anything meaningful; instead you'd get some weird result at runtime. Adding thevoidtype:allows the compiler to catch mistakes like that and issue a diagnostic.
A happy side effect of adding the
voidtype is getting thevoid *type, which sort of acts as a "generic" pointer type. In K&R C,char *was used as the default pointer type for things likemalloc,qsort, etc. Unfortunately this meant you had to explicitly cast everything if you were working with anything other thanchar *:Along with adding the
voidtype, C89 introduced a rule thatvoidpointers could be assigned to other pointer types and vice-versa without needing an explicit cast. So now you can usemallocandqsortet al. without having to cast everything to hell and gone:Since the result of dereferencing a
void *is avoidexpression, you can't access data through avoid *, even if it's pointing to a valid object; you have to assign it to the right object pointer type first:1
u/khalon23 Jul 29 '26
voidis a type that means "no value". As a return type it means the function does not return anything useful. As a parameter listfoo(void)in C means no parameters (emptyfoo()is a legacy thing that means unspecified parameters in old C).void *is a generic object pointer: you can convert to/from other object pointers without a cast in C, but you cannot dereference avoid *until you cast it to a real type. It is not a "value type" you store bytes in; it is a pointer type with no element size.1
u/Top-Satisfaction9950 Jul 29 '26
void means the function does not return anything.
void* means that the function returns a pointer to an unknown-size block of data. It's a location. It also means that a variable stores a pointer to an unknown-size block of data. Use them for generic programming; they're very useful that way :D
But be careful.
1
u/cards88x Jul 29 '26
Thanks for posting this. Coming from an assembly background, Im still getting used to the requirement that everything be declared upfront
1
u/erroneum Jul 29 '26
voidis nothing. In a function definition, it indicates the absence of a return value, or explicitly the absence of parameters. As a pointer type, it indicates that the pointer doesn't point to any known object type (pointer to nothing).If you have
void *p, then there's no context in which you can write(*p)to dereference it, because the compiler has no clue what is there to find (if anything). To do anything with it, you first need to cast it to a pointer to complete type, either explicitly or implicitly.1
u/Ragingman2 Jul 30 '26
https://thecodelesscode.com/case/5
1
u/NoSpite4410 Jul 30 '26
Void is a return type of no value. C had to have a return type for every function, so they used that.
Before C, the concept of a function was a set of operations that took in fixed input values, performed a calculation, and returned a new fixed value. The inputs were immutable, and that is all the function could do was to produce a new value. Procedures were operations on existing values, that changed them, but did not return new values. Procedures also could execute Commands -- statements that made the machine do something that would change the state of the machine and how it behaved, as well as altering existing values.
This was very "clean" and separated concerns, made perfect sense from a math perspective where functions never altered their input variables, etc.
But C was designed for speed, and to take advantage of changing hardware that had more tricks it could do, etc. So they dispensed with the separation, and just made the function do whatever, change things like inputs, perform system commands, return values, or act like a procedure and have no return value.
Pointers were introduced into the C language, to allow all kinds of optimal hacks and so on. One hack was to have a void pointer type, which is a "non-value" type, a handle to raw memory. This had the side effect of being able to "type erase" whatever was at that memory address, and so they put in some rules to make at least an attempt to tame such a wild feature: you must cast a void pointer to a known value type before reading or assigning it values, and you may cast a void pointer to any known type regardless of the size of the type. This allows one to take structs and strings and so on and read and write them to disk and around the memory as raw bytes, through "type erasure" and "type reconstitution" via a void pointer. Later they relaxed the rules around char pointer to make it almost as universal, because char is 1 byte long, so the correspondence is the same as raw bytes. So most "raw buffers" you see in source code are char arrays. The final rule of C that makes it all work is that you are free to ignore the return value of any function, and often do. printf for instance returns integer, but is usually ignored.
1
u/-H_- Jul 30 '26
I plan to clear this up with my teaching order used in my book but here's the basic idea
Void is just a type that occupies no memory. The c standard also dictates that the compiler shouldn't let anything with type void actually exist. Pointer to void is allowed though, and it can be cast to all other pointer types freely
1
u/logic_circuit Jul 30 '26
Twilight zone or anything you want it to be. Make your choice by proper cast.
0
u/sciencekm Jul 29 '26 edited Jul 29 '26
It means none.
void f(void);// no parameter, no returnvoid *p;// pointer to no typevoid g(int n) {(void)n;// no operation; no use(void)puts("");// no use for the return}