"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Void Pointers in C and C++: Why are Implicit Conversions Different?

Void Pointers in C and C++: Why are Implicit Conversions Different?

Published on 2024-11-20
Browse:560

  Void Pointers in C and C  : Why are Implicit Conversions Different?

Understanding Void Pointers: Differences Between C and C

Void pointers are a key aspect of both C and C , but there are notable differences in their handling. This article explores these differences and explains why seemingly contradictory behaviors can occur.

Implicit Conversions in C

In C, conversions between a pointer to a specific type (e.g., int) and a void pointer (void) are always implicit. This means that the following statement is valid:

int* p = malloc(sizeof(int));

The malloc function returns a void*, which is then assigned to the int* pointer. However, in C , such implicit conversions are not permitted.

Explicit Casting in C

In C , converting from a pointer to a void pointer is still implicit, but converting from a void pointer to a specific type requires an explicit cast. This explains why the following code compiles in both C and C :

void foo(void* vptr)
{
}

int main()
{
    int* p = (int*) malloc(sizeof(int));
    foo(p);
    return 0;
}

The malloc function returns a void*, which is passed to the foo function. Even though the int* pointer is assigned to the void* parameter, C allows this implicit conversion. However, the subsequent call to p requires an explicit cast to the int* type.

The Standard's Perspective

According to the K&R2 specification, any pointer to an object can be safely converted to void* without information loss. Furthermore, converting back to the original pointer type restores the original value. In C , the standard specifies that implicit conversions from any pointer type to void* are allowed, but explicit casting is necessary for conversions from void* to any other type.

Conclusion

The key difference between C and C void pointer handling lies in the requirement for explicit casting when converting from void* to a specific type in C . This stricter approach helps prevent undefined behavior and maintains type safety in C code.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3