-2

Why is compiler saying that this is not pointer:

#include <stdio.h>

double f(){ return 1.2; }
int main(){

    int i=0;
    double d =f()[0]; //f() is not pointer? it should be
    printf("%i\n",d);
}

error:

subscripted value is neither array nor pointer nor vector
  double d =f()[0];

But is I have declared a function pointer, and then used a name of a function, then it will become pointer:

#include <stdio.h>

int op(int (*op)(int,int), int a, int b){ return op(a,b); }
int add(int a, int b){ return a+b; }

int main(){
    printf("%i\n",op(add, 1, 2)); //here: add() will magically become pointer, different context
}

So in first case, I wanted to dereference the function, in hope, the name of the funtion is pointer (and so derefencing is permitted). In second example, the function pointer is declared with pointer, so the function add will decay to pointer (compare to printf("%i\n",op(&add,1,2))) will also work. So why is problem with the first one?

milanHrabos
  • 2,010
  • 3
  • 11
  • 45

1 Answers1

1

For a function f, or callable in general, f() is calling the function and evaluates to the type declared as the functions return type. Functions can decay to pointer to function, similar to arrays, but when you call the function, this doesn't happen:

int foo(int,int){ return 1;}

int main() {
    using fptr = int (*)(int,int);
    fptr p = foo;                    // <- function pointer (note: no & needed because it decays to function pointer)
    fptr q = &foo;                   // <- also function pointer
    int x = foo(1,2);                // <- function call
}

In your examples:

double d =f()[0]; //f() is not pointer? it should be

No, f() is not a pointer. f returns a double.

printf("%i\n",op(add, 1, 2)); //here: add() will magically become pointer, different context

No. add() will not magically become a pointer. add is the function that will automagically decay to function pointer (acutally it isnt that "magic").

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185