I recently stumbled across an interesting question (at least i think it is). A little example:
Example
#include <stdio.h>
typedef struct A {
int x;
} A;
int (*func)(void*, void*);
int comp(A* a, A* b) {
return a->x - b->x;
}
int main() {
func = comp;
A a;
A b;
a.x = 9;
b.x = 34;
printf("%d > %d ? %s\n", a.x, b.x, func(&a, &b) > 0 ? "true" : "false");
}
I asked myself if the above shown is valid code but on compilation GCC threw a warning: warning: assignment from incompatible pointer type. I did some research and in one thread someone stated the above would be undefined behaviour now im curious why this is UB since void* can be casted savely to any possible other type. Is it just the standard saying "Nope thats undefined" or is there some explainable reason? All questions on StackOverflow I found state its UB but not exactly why. Maybe it has something to do how a function pointer is dereferenced internally?