4 ms·
What can you do with a void pointer without casting it, apart from comparing it to NULL?
by throwphoton 6y ago
What can you do with a void pointer without casting it, apart from comparing it to NULL?
- eMSF 6y agoYou can (implicitly) convert it to another pointer type, e.g. int *buf = malloc(sizeof(*buf)); (It's noteworthy that while there's an implicit conversion above, there's no such thing as an implicit cast.)
- microtherion 6y agoYou can assign it to any data pointer variable, and you can printf("%p") it, for example.
- unwind 6y agoThis is a pretty well-regarded answer, with motivation for why you should not cast [1]. Of course it's not something everyone agrees to, but at least a lot of people seem to. [1] https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc https://stackoverflow.com/questions/605845/do-i-cast-the-res...
- throwphoton 6y agoInteresting. Not casting a void pointer return value seems like a bit of a shibboleth for the "C is not a subset of C++" community.
- enriquto 6y agoA "better" shibboleth is using "new" and "old" as identifiers. It serves as a good barrier to avoid accidental C++ compilation.
- _kst_ 6y agoYou can compare it for (in)equality to another void pointer.
- glouwbug 6y agoGeneric data structures work great if they use a void* since malloc returns a void*. Just malloc your structs, and suddenly a single set of 10 or so functions can work with all data types to build queues, lists, hash maps, etc