Function to void pointer conversion*

Asked

Viewed 140 times

8

Recently, I was trying to solve a problem in a program of mine in C and, by chance, I came across some answers from Stack Overflow in English which stated that converting a pointer to a function to a void pointer* is illegal in C.

My English is not much and the answers I have visited are old, so I am not sure I have understood the right information or if the answers have become outdated with C11. Anyway, I leave the links c-cast-void-Pointer-to-Function-Pointer and c-Function-Pointer-casting-to-void-Pointer

But if I understood it right, this, in my case, is particularly worrying because the truth is that I find this conversion extremely practical and more than once I’ve been converting void* for pointers like int (*f)(int, int).

Not to be too abstract, an example of this type of conversion below:

#include <stdio.h>

int sum(int a, int b){
    return a + b;
}

int main(){
    void* foo = &sum;
    int (*f)(int, int) = foo;
    printf("Esta soma e ilegal? Soma = %d\n", f(10, 8));
    return 0;
}

And it’s not only worrying, it’s weird also since the above code compiles and works perfectly on Devc++, Codeblocks and VS2019, on my Windows 10 machine.

Based on that, my question is: the pointer conversion void* for pointer to function is in fact not allowed by the standard C and the fact that the above code works on my machine is no guarantee that it will work on other implementations or I have misread the articles and the conversion is allowed by the standard C?

1 answer

4


It is allowed to do this by default, only it is not mandatory, so some compilers may or may not leave it and may even leave it only where it makes sense. Even if the compiler leaves it may not make sense, or may cause problems in certain situations. I always remember:

Fiat 147 todo detonado andando pelas ruas

Have compiler that does not accept. But depends on configuration. But look at what beauty when the signature is not compatible.

#include <stdio.h>

int sum(int a, int b) {
    return a + b;
}

int main() {
    void* foo = &sum;
    int (*f)(int, long long) = foo;
    printf("Esta soma e ilegal? Soma = %d\n", f(10, 1000000000000L));
}

I put in the Github for future reference.

It’s not that the void * let this happen, is that if the compiler lets something irregular pass he leaves others, he is more insecure than the others. There is reason to use compilers with looser rules, but most of the time you will prefer to use a more restrictive one and save yourself huge headaches.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.