int (*ptr)();
Can someone ELI5 what this code snippet does? I find it almost impossible to visually or logically make sense of it.
Also how and when is it used?
int (*ptr)();
Can someone ELI5 what this code snippet does? I find it almost impossible to visually or logically make sense of it.
Also how and when is it used?
It's a pointer, named ptr, to a function that returns an int and takes no arguments (i.e., int ()
).
The syntax isn't beautiful, but it's like a function signature, except the second part identifies that this is a pointer to such a function, with a certain name (ptr in this case).
This tutorial might be of help in understanding the principles (excerpt follows):
int (*pt2Function)(float, char, char) = NULL; // C
int DoIt (float a, char b, char c){ printf("DoIt\n"); return a+b+c; }
int DoMore(float a, char b, char c)const{ printf("DoMore\n"); return a-b+c; }
pt2Function = DoIt; // short form
pt2Function = &DoMore; // correct assignment using address operator
Read it from inside to outside.
(*ptr)
- it's a pointer variable named ptr
. Replace it with some symbol, say A.
int A();
- it's a function taking no arguments and returning int
.
Now recall what A is. Combine it. The answer is: this declares a variable, named ptr
, which is a pointer to a function that takes no arguments and returns int
.
It is a function pointer, which points to a function that returns an int type.
Before calling a function through a pointer, it is necessary to initialize the pointer to actually point to a function.
Here is an example of calling 'atoi()' using a function pointer:
#include <stdio.h>
#include <stdlib.h>
int (*ptr)(const char *nptr) = atoi;
int main()
{
printf("%d\n", (*ptr)("42");
return(0);
}