Using Function Pointers

Possible duplicate:
How does the function pointer dereference occur?

Hello everyone, Why do 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));
}

Conclusion:

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));
}

Conclusion:

the value is 7
the value is 3
the value is 10
+3
source share
3 answers

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

Considering

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 the name of the function is "function designation". 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, this dereferencing is also a “function designation”. From the standard:

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

, f(5,2) (*f)(5,2) . call to function designated by f with parms (5,2) . f(5,2) (*f)(5,2) .

+5

, .

+3

you do not need to use and before the function name

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

however, both paths are valid.

+2
source

Source: https://habr.com/ru/post/1749950/


All Articles