write_fn b1 = (write_fn) write_b; // is this legal?
Is it legal?
The types of function pointers involved in this cast are incompatible.
However, a cast function pointer to an incompatible type of function pointer is completely legal. However, the only thing you can do with such a strongly transformed pointer is to return it back to its original type. The language specification ensures that such a round-trip conversion preserves the original value of the pointer. That is why we can use, say, void (*)(void)
as the "universal type of storage" for function pointers (for example, void *
for data pointers). It can be used to store function pointers of any type (but not to call functions). To perform such a repository of pointers (and search), we will have to use explicit casts, as in your code. Nothing illegal there.
Meanwhile, an attempt to call a function through b1
will lead to undefined behavior, in particular, because the type of the pointer is incompatible with the actual type of the function.
In your question, you clearly state that you want to "save" a pointer to this function. While we are only talking about βsavingβ (storing) a pointer, your code is completely flawless.
source share