What does the following C-statement declare? [1 mark] int ( * f) (int * ) ;
2005
What does the following C-statement declare? [1 mark]
int ( * f) (int * ) ;
- A.
A function that takes an integer pointer as argument and returns an integer.
- B.
A function that takes an integer as argument and returns an integer pointer.
- C.
A pointer to a function that takes an integer pointer as argument and returns an integer.
- D.
A function that takes an integer pointer as argument and returns a function pointer
Attempted by 157 students.
Show answer & explanation
Correct answer: C
Answer: This declares f as a pointer to a function that takes a pointer to int (int *) as its argument and returns an int.
Key points:
The parentheses around *f (i.e., (*f)) make the * apply to the identifier f, so f is a pointer.
Function declarators bind tighter than the * operator, so int (*f)(int *) means ‘‘pointer to function’’ rather than ‘‘function returning pointer’’.
For contrast: int f(int *); declares a function f that takes int * and returns int. int *f(int); declares a function returning int *.
Example usage:
Define a function matching the type: int foo(int *p) { return *p + 1; }
Assign and call through the pointer: f = foo; int x = 2; int y = f(&x);