Sam Claus
Sam Claus

Reputation: 1981

Does C's void* serve any purpose other than making code more idiomatic?

Does C's void* lend some benefit in the form of compiler optimization etc, or is it just an idiomatic equivalent for char*? I.e. if every void* in the C standard library was replaced by char*, would anything be damaged aside from code legibility?

Upvotes: 2

Views: 147

Answers (3)

chux
chux

Reputation: 153488

Does C's void* serve any purpose other than making code more idiomatic?

if every void* in the C standard library was replaced by char*, would anything be damaged aside from code legibility?

C11 introduced _Genric. Because of that, _Generic(some_C_standard_library_function()) ... code can compile quite differently depending on if the return type was a void *, char *, int *, etc.

Upvotes: 1

Barmar
Barmar

Reputation: 781004

In the original K&R C there was no void * type, char * was used as the generic pointer.

void * serves two main purposes:

  1. It makes it clear when a pointer is being used as a generic pointer. Previously, you couldn't tell whether char * was being used as a pointer to an actual character buffer or as a generic pointer.

  2. It allows the compiler to catch errors where you try to dereference or perform arithmetic on a generic pointer, rather than casting it to the appropriate type first. These operations aren't permitted on void * values. Unfortunately, some compilers (e.g. gcc) allow arithmetic on void * pointers by default, so it's not as safe as it could be.

Upvotes: 5

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

C got along just fine for years with char * as the generic pointer type before void * was introduced later. So it clearly isn't strictly necessary. But programming languages are communication--not just telling a compiler what to do, but telling other human beings reading the program what is intended. Anything that makes a language more expressive is a good thing.

Upvotes: 3

Related Questions