3

Please look at the code following:-

 #include <stdio.h>
 int sum ( int b, int a){
 return (a+b);
  }
 int main(){
 int (* funptr)( int , int ) = sum;
 int a = ( * funptr )( 4,5);
 int b = funptr (4,5);
 printf("%d\n%d",a,b);
 return 1;
 }

Is there any difference between the two function calling via pointer,one is

int a = ( * funptr )( 4,5);

and another is

int b = funptr (4,5);

As i have compiled this code and result is same in both the cases.Is this means that these are equivalent?

3
  • They are identical, but personally I always use the (*funcptr)(...) form to make it explicit that I am dereferencing a pointer. Makes it clearer to the reader that it isn't a function with that actual name. Commented Mar 30, 2014 at 20:37
  • @Dave so dereferencing the function pointer yields the same value as without dereferencing? Commented Mar 30, 2014 at 20:39
  • Yes. As I said, "They are identical" Commented Mar 30, 2014 at 20:40

2 Answers 2

2

In case of function pointer:

Function Pointer is very flexible to use.. You can put value into it with or without the & operator, and call the stored function through pointer with or without * operator.

e.g,

int (* funptr)( int , int ) = sum;   // or int (* funptr)( int , int ) = &sum;
int a = ( * funptr )( 4,5);          // or int a = funptr( 4,5);

Hope it helped...

Sign up to request clarification or add additional context in comments.

4 Comments

int (* funptr)( int , int ) = *sum; //or **sum is also equivalent?
Yes... You can put as many * as you want before sum it all will result same...
i have seen these statement written before few times what that mean by *sum as so what is the difference between sum and *sum and **sum?
if, as your previous example, sum is a function, and it is asked to differentiate sum and *sum, in this case actually *sum makes no sense, compiler just ignores the * operator in such case..
2

Due to historic differences how to take the address of a function, you can apply address of and dereference any time you want to a function name, without any effect whatsoever.

Also, dereferencing a function pointer has no effect at all.

So, yes, your examples are equivalent.

8 Comments

so these two calling statements are equivalent?
yes, they are equivalent. BTW: Get the standard: open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
int (* funptr)( int , int ) = *sum; //or **sum is also equivalent?
They are not equivalent to previous examples, but your two new examples are equivalent to each other...
oh! conflict between your and deb_rider comment please look at the comment of his answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.