Home > Backend Development > C++ > body text

Void Pointers in C and C : Why Does Casting Matter?

Linda Hamilton
Release: 2024-10-30 12:39:26
Original
1001 people have browsed it

 Void Pointers in C and C  : Why Does Casting Matter?

Void Pointers in C and C : Unveiling the Differences

When working with pointers, there are noticeable discrepancies between C and C syntax, particularly in regard to void pointers. In C, the assignment of a void pointer to a pointer of another type is permissible, while in C it requires an explicit cast.

Consider the following example:

<code class="c">int* p = malloc(sizeof(int));</code>
Copy after login

This code compiles successfully in C because malloc returns a void pointer, which can be safely assigned to an integer pointer in C. However, attempting the same in C will result in a compilation error.

However, in a different context, the following code compiles in both C and C without issue:

<code class="c">void foo(void* vptr)
{
}

int main()
{
    int* p = (int*) malloc(sizeof(int));
    foo(p);
    return 0;
}</code>
Copy after login

This discrepancy stems from the implicit and explicit pointer conversions in C and C , respectively. In C, both conversions are implicit, allowing an easy transition between pointer types. However, in C , while conversions from a pointer type to a void pointer remain implicit, conversions in the opposite direction require an explicit cast.

This distinction is highlighted in the C language's reference manual (K&R2), which explicitly states that only conversions from an object pointer to a void pointer are supported without information loss.

In comparison, the C standard dictates more stringent rules, mandating an explicit cast when converting from a void pointer to any other pointer type, thus ensuring type safety and preventing potential pointer errors.

The above is the detailed content of Void Pointers in C and C : Why Does Casting Matter?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!