Open In App

How does ‘void*’ differ in C and C++?

Last Updated : 28 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

C allows a void* pointer to be assigned to any pointer type without a cast, whereas in C++, it does not. We have to explicitly typecast the void* pointer in C++

For example, the following is valid in C but not C++: 

void* ptr;
int *i = ptr; // Implicit conversion from void* to int*

Similarly,

int *j = malloc(sizeof(int) * 5);  // Implicit conversion from void* to int* 

In order to make the above code compile in C++ as well, we have to use explicit casting, as shown below,

void* ptr;
int *i = (int *) ptr;
int *j = (int *) malloc(sizeof(int) * 5);


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads