0
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?

aknuds1
  • 65,625
  • 67
  • 195
  • 317
Jebathon
  • 4,310
  • 14
  • 57
  • 108

3 Answers3

4

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
aknuds1
  • 65,625
  • 67
  • 195
  • 317
  • 2
    As for how you might use it, you might implement two functions that take `void` and return `int` that represent two ways to roll dice. Depending on control flow in the program, you might want to switch to normal or cheating dice. Using a function pointer, you avoid needing an if-else statement in the implementation and can instead assign the pointer directly, e.g. `int CheatingRoll(){...} ... ptr = &CheatingRoll;` – MooseBoys May 07 '14 at 00:39
  • @MooseBoys lol cheatingdice. I took int (*ptr)(); from a Remote ShellCode Launcher. Close enough – Jebathon May 07 '14 at 00:59
1

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.

nullptr
  • 11,008
  • 1
  • 23
  • 18
0

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);
    }
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28