5
    #include <stdio.h>

    int add(int a, int b)
    {
        int c =a+b;

        return c;
    }

    int main()
    {
        int a=20,b=45;
        int (*p)(int , int);
        p=&add;

        printf("%d\n%d\n%d\n\n",*add,&add,add);
        printf("%d\n%d\n%d\n\n",*add+1,&add+1,add+1);


        return 0;
    }

Outupt is

4199392 4199392 4199392

4199393 4199393 4199393

So why the *add, &add, add are same? I also doubt that 'add' act like an array, correct me if I am wrong, because, address of array and array itself are same.

  • Because this is the C programming language. It is what it is. Similarly: why don't oil and water mix? Because they don't. – Sam Varshavchik Feb 12 '16 at 03:11
  • 1
    The code invokes undefined behavior anyway. The `printf` format specifier for a function pointer is not `%d`. – PaulMcKenzie Feb 12 '16 at 03:12
  • Printing out pointers by `%d` causes undefined behavior in C, in which case anything can happen. – nalzok Feb 12 '16 at 03:13
  • The name of the function is a pointer to it; ergo, the operators * (dereference) and & (return pointer AKA memory address) are useless. If you want to get the pointer to a function, only use it's name. What I can't answer, however, is why using *add and &add doesn't end up in an error or at least a warning. I can suppose the compiler ignores such operations in function pointers, but can't confirm it. – Judismar Arpini Junior Feb 12 '16 at 03:27
  • About the array: address of array is a pointer/memory address, and an array is a data structure in which multiple data of the same type can be stored. They are not the same. – Judismar Arpini Junior Feb 12 '16 at 03:28
  • It's pretty much the same as arrays - `add` "decays" to `&add`. – user253751 Feb 12 '16 at 03:39

2 Answers2

0

In C the only things you can do with a function is to call it or taking its address. So if you aren't calling it, you're pretty much taking its address.

John Hascall
  • 9,176
  • 6
  • 48
  • 72
0

"C11 §6.5.6 Additive operators" /6 discusses adding to a pointer

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, ... . If the result points one past the last element of the array object, ...

Nowhere does the C spec define adding an integer type to a function pointer. Thus undefined behavior.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256