-1

I am trying to understand exactly what this line of code is, as I am learning C.

int (*f) (float *)

I know the first part is a pointer to an int named f, however the second part is what I am unsure of.

Would this be classed as a pointer to an int named f which is cast to a pointer-to-float

or

Would this be a pointer named f, pointing to a function with a pointer parameter.

Would be great if someone could help and possible explain why or the difference between the two as I am having a little trouble understanding this concept.

Thanks!

stark
  • 12,615
  • 3
  • 33
  • 50
madhaj1
  • 35
  • 1
  • 1
  • 8
  • Possible duplicate of [Tool to explain C code](http://stackoverflow.com/questions/667362/tool-to-explain-c-code) – Jongware May 13 '16 at 18:25

4 Answers4

3

That line declares f as a pointer to a function accepting a float * as its argument and returning an int.

The declaration may seem tricky, but it is just following the rules of C. If we wrote

int *f(float *);

Then it would seem as though f is a function returning int *. Thus, the correct precedence must be forced using parenthesis around *f.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
2

Here is an example of how f is defined, assigned a function pointer, and then called

#include <stdio.h>

int foo(float *real)
{
    float num = *real + 0.5F;
    return (int)num;
}

int main(void)
{
    float number = 4.9F;
    int (*f) (float *) = foo;           // define f
    printf("%d\n", f(&number));         // calls f
    return 0;
}

Program output:

5
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • I went with the question, but it would have been clearer without a pointer argument `*real` (which I didn't put to good use) giving one more `*` than is really necessary to illustrate the use of a function pointer. – Weather Vane May 12 '16 at 21:21
1

It declares f as a pointer to a function taking a float * (a float pointer) and returning int. You can then use it like this

float array[5] = {1.0, 2.0, 3.0, 4.0, 5.0};
printf("%d\n", f(array));
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
1

If you had the declaration:

int foo(float *);

it would be clear that it was a function definition. Using (*f) instead of foo gives you a pointer to a function.

stark
  • 12,615
  • 3
  • 33
  • 50