views:

132

answers:

4

Possible Duplicate:
How does dereferencing of a function pointer happen?

Hi All, Why these two codes give the same output, Case 1:

#include <stdio.h>

typedef void (*mycall) (int a ,int b);
void addme(int a,int b);
void mulme(int a,int b);
void subme(int a,int b);

main()
{
    mycall x[10];
    x[0] = &addme;
    x[1] = &subme;
    x[2] = &mulme;
    (x[0])(5,2);
    (x[1])(5,2);
    (x[2])(5,2);
}

void addme(int a, int b) {
    printf("the value is %d\n",(a+b));
}
void mulme(int a, int b) {
    printf("the value is %d\n",(a*b));
}
void subme(int a, int b) {
    printf("the value is %d\n",(a-b));
}

Output:

the value is 7
the value is 3
the value is 10

Case 2 :

#include <stdio.h>

typedef void (*mycall) (int a ,int b);
void addme(int a,int b);
void mulme(int a,int b);
void subme(int a,int b);

main()
{
    mycall x[10];
    x[0] = &addme;
    x[1] = &subme;
    x[2] = &mulme;
    (*x[0])(5,2);
    (*x[1])(5,2);
    (*x[2])(5,2);
}

void addme(int a, int b) {
    printf("the value is %d\n",(a+b));
}
void mulme(int a, int b) {
    printf("the value is %d\n",(a*b));
}
void subme(int a, int b) {
    printf("the value is %d\n",(a-b));
}

Output:

the value is 7
the value is 3
the value is 10
+3  A: 

Because function pointers are automatically resolved whether you use them with or without the dereference operator.

John Weldon
+1  A: 

The two are equal. You can do:

foo( 2 );

or

 (*foo)( 2 );

it's the same

Polybos
You can also do `(**********foo)(2);` :)
FredOverflow
+2  A: 

you don't have to use & before function name

x[0] = addme;
x[1] = subme;
x[2] = mulme;

however both ways are valid.

noisy
+3  A: 

I'll simplify your question to show what I think you want to know.

Given

typedef void (*mycall)(int a, int b);
mycall f = somefunc;

you want to know why

(*f)(5, 2);

and

f(5.2);

do the same thing. The answer is that a function name both represent a "function designator". From the standard:

"A function designator is an expression that has function type. Except when it is the
operand of the sizeof operator or the unary & operator, a function designator with
type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to
function returning type’’."

When you use the indirection operator * on a function pointer, that dereference is also a "function designator". From the standard:

"The unary * operator denotes indirection. If the operand points to a function, the result is
a function designator;..."

So f(5,2) becomes essentially (*f)(5,2) by the first rule. This becomes call to function designated by f with parms (5,2) by the second. The result is that f(5,2) and (*f)(5,2) do the same thing.

Tim Schaeffer
think you have a small typo, *mycall ---> myfunc
reuscam
@reuscam: fixed, thanx.
Tim Schaeffer