3

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
Community
  • 1
  • 1
chaitanyavarma
  • 315
  • 2
  • 4
  • 8

3 Answers3

5

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
  • 2,616
  • 1
  • 16
  • 20
3

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

John Weldon
  • 39,849
  • 11
  • 94
  • 127
2

you don't have to use & before function name

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

however both ways are valid.

noisy
  • 6,495
  • 10
  • 50
  • 92