Re: Casting function pointers



KKL wrote:
I wonder how casting with function pointers work, how it "should be"
handled and how it "should not be" handled. Can anyone tell whether
the below code should work or not?

<snip>
My question is whether these kind of casting for function pointers is
valid. If valid should it work with a predictable behavior or the
behavior is undefined.


It's also important to note that function pointers are not directly compatible with data pointers - you can't necessarily convert a function pointer to a void* and back again, and expect a valid result (although it should work in practice, at least on 32-bit processors). You can't ever convert a method pointer to a function pointer (unless it's a static method).

Personally, I think phrases such as "(void ()(void)* ) funcPtr" are ugly and hard to read. Use typedefs - they make your code clearer, minimise mistakes, and make it easier to change later:

typedef void (*FVoid)(void);

int taskCreate(char* taskName, FVoid funcPtr, ....)
.



Relevant Pages

  • Re: User defined stack for threads in Linux 2.6.11 + glibc 2.3.5
    ... printf, sleep(), and pthread_exitaren't async-cancel-safe, so the ... behavior is undefined if the thread running that code is actually ... The casting of 'fn' to void* is actually a constraint violation. ... structure that holds the function pointer and the value to pass as its ...
    (comp.programming.threads)
  • Re: Function Pointers
    ... that a function pointer contains the memory address of the function. ... typedef void; ... void foo ...
    (comp.lang.c)
  • Re: returning function pointer
    ... function pointer some_func & meanwhile calls that function and prints ... void some_func ... int main ... Note there are two parameter lists here. ...
    (comp.lang.c)
  • Re: Common misconceptions about C (C95)
    ... I have never seen an example of function pointer ... and void pointer have any interaction. ... Great programmers make ... over the C programming world and only someone of very limited experience ...
    (comp.lang.c)
  • Re: Passing a pointer to a function to the function it points to
    ... void* can't be used because it might not be able to represent a ... Any type of function pointer can portably losslessly point to any ... (Identical to is the easiest form of compatibility.) ...
    (comp.lang.c)