cfunctionpointerscastingvoid-pointers

Auto cast void pointer to pointer to double in function call


I have a question, and it might already be answered somewhere else, and I could not find it, so I apologize if it already exists.

I have the following code:

#include <stdio.h>

void foo(double *number) {
    printf("%f\n", *number);
}

void bar(void *number) {
    double *new_number = (double *)number;
    printf("%f\n", *new_number);
}

int main()
{
    double test_number = 3.0;
    double *test_double_pointer = &test_number;
    void *test_void_pointer = (void *)test_double_pointer;
    
    foo(test_double_pointer);
    foo(test_void_pointer);
    bar(test_double_pointer);
    bar(test_void_pointer);

    return 0;
}

the result is

3.000000
3.000000
3.000000
3.000000

I don't understand what is happening under the hood. How does the C compiler handle these function calls?


Solution

  • Your code is a good example of how to use void pointers to pass data of any type between functions.

    §6.3.2.3 Pointers (C11 N1570)

    1. A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

    Not much happening under the hood, compilers must assure the above rule is respected. An easy way is to do this is to have all pointer types be the same size.

    Importantly, the compiler also needs to know the pointer type in order to perform the usual pointer arithmetic and operations.