Re: Cannot understand the following codes



Ben C wrote:
On 2006-03-28, Alf P. Steinbach <alfps@xxxxxxxx> wrote:
* Ben C:
On 2006-03-28, Alf P. Steinbach <alfps@xxxxxxxx> wrote:
It's probably a void(*)(). But not matter what type it has, the cast is undefined behavior in C++, and I believe also in C.
Why's it undefined behaviour? I can see that it invites undefined
behaviour, but not that it entails it-- if the value of
stGOFuncs.p_go_Measurements is a function of the correct type won't it
be OK?
It will be OK, /if/ the type is some pointer to function (but not if the type is simply void*, in which case it's UB); I was too hasty there.

You're right, void * and function pointers are not compatible. I tried
this:

#include <stdio.h>

int f(int x)
{
return x * 2;
}

int main(void)
{
int (*q)(int) = f;
void *p = q; /* WARNING */
int (*r)(int) = p; /* WARNING */

int x = (*r)(3);

printf("Answer is %d\n", x);

return 0;
}

I had assumed void * was good for anything. But it's only good for data,
not functions.

I suppose on some machines functions might have a completely different
address space, be a completely different size etc., and the standard is
allowing for that...

Sorry about that... ;-)

Not at all, thank you, I was missing something.

Pedantically void pointers and function pointers are not compatible. But is a less pedantic world it might work.. if you change your line

int x = (*r)(3);

to

int x = (r)(3); or even

int x = r(3);

--
Joe Wright
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
.



Relevant Pages

  • Re: Malloc code
    ... int xxx; ... As for not using the void pointer, I will have to do some further testing ... I just needed some insight on passing arrays of pointers. ... struct MCB *r1; ...
    (microsoft.public.vc.language)
  • Re: Using a link list over an array.
    ... compile (p->data is a void *) so you have not shown us some key ... You can't use it to sort a list of ints where the int is ... You can use it to sort a list of pointers to any type. ...
    (comp.lang.c)
  • Re: void *
    ... list_add_head(&p, (int *)100); ... That was my understanding of 'void *' concept. ... In fact at your level the first thing you should assume when you appear to need a cast is that you have done something wrong and a cast is *not* the solution. ... Personally I don't think you understand the concept of pointers yet, so you need to read the sections of your text book and the comp.lang.c FAQ that refer to pointers. ...
    (comp.lang.c)
  • Re: Function call evaluation order
    ... void f1 ... int i = 0; ... f1 has.completely undefined behavior since i is modified twice ...
    (microsoft.public.vc.language)
  • Re: How are C++ objects laid out in memory ?
    ... > void print(); ... int main ... > But the function pointers declared in above MsgStruct structure have ... > pointers which I can locate and then invoke the function pointers? ...
    (comp.lang.asm.x86)