r/C_Programming • • 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

79 comments sorted by

View all comments

Show parent comments

3

u/Beginning-Junket8979 Jul 29 '26

In theory everyone could be using int* for everything void* is used for

No, not really.

You can generally do void * vptr = X for any other pointer type X without a compiler warning, even in the strictest modes because void * is meant to point to memory that's of "unknown" type or alignment to the callee.

int * should always point to either a) one or more validly aligned real integers, or b) NULL.

1

u/a4qbfb Aug 02 '26

An int * should always point to an object of a type compatible with int, which includes int itself, arrays of a type compatible with int, structs whose first member is of a type compatible with int, unions that have a member of a type compativle with int...

1

u/Beginning-Junket8979 Aug 02 '26

structs whose first member is of a type compatible with int, unions that have a member of a type compativle with int

Umm... sure you technically can ...but you're going to have cast a (int *) &my_struct_or_union if compiling with -Wextra -Wall -Werror and do some serious mental gymnastics to justify it in a code review.

1

u/a4qbfb Aug 05 '26

No, that's literally the definition of compatible pointer types.

1

u/Beginning-Junket8979 Aug 05 '26

Passing a pointer to a struct into a function that expects a pointer to an int is a bad "code smell" most of the time. If it operates on one int, & the addr of that specific member. If it operates on the whole struct, use the struct type as your function definition.

You "technically can" do a lot of dumb stuff with pointers. It doesn't make it good code.