Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the reasons for casting a void pointer?

Tags:

c

I'm learning C++ from scratch, and as such I don't have an expert understanding of C. In C++, you can't cast a void pointer to whatever, and I understand the reasons behind that. However, I know that in C, you can. What are the possible reasons for this? It just seems like it's be a huge hole in type safety, which (to me) seems like a bad thing.

like image 859
Maulrus Avatar asked Apr 07 '10 06:04

Maulrus


1 Answers

You can cast a void* to another pointer in both languages. Perhaps you meant implicitly.

It's very convenient in C to not have to be explicit about it. In C++ we have templates, so to write generic code there's no need for void* casting and whatnot. In C there is no choice. A generic container has to hold void* to objects, and it's much easier to repeatedly say mydata* d = node; then it is mydata* d = (mydata*)node;.

So it's pretty much like you said. In C type safety in general didn't receive as much emphasis as it did in C++, especially when it came to void* because it was suppose to be a simple generic pointer to whatever. There's no need for that in C++, so better make it explicit when you're dealing with it.

like image 125
GManNickG Avatar answered Oct 12 '22 19:10

GManNickG