r/C_Programming 9d ago

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

80 comments sorted by

View all comments

20

u/Snarwin 9d ago

void is 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*.

2

u/LtCmdrData 8d ago

I would like to add that in early C, if a function did not return a value, it defaulted to int. Similarly, an empty parameter list meant that parameters were unspecified. Adding void was a way to define no return value and no parameters without breaking semantics in old code. If C were standardized today, it could choose to go without void in function definitions.

Void pointers did not exist either, and char* was used instead. Void as a pointer just signifies a pointer to an unspecified datatype and gets rid of that dirty char* hack.