0

I am trying to define a type for function pointers, in c++. However, once I define the pointer funcp as a fptr, I cannot redefine the pointer as a different function, times. This program does not even compile. Is this because I have to delete the nullptr before reassigning times to funcp?

My code:

#include <iostream>
using namespace std;

typedef int (*fptr)(int, int);

int times(int x, int y)
{
    return x*y;
}

fptr funcp = nullptr;

funcp = times;

int main()
{
    return 0;
}
littlecat
  • 103
  • 4
  • if you move the assignment funcp = times; inside main then it will work. your problem is a scoping issue. – Paul Baxter Jul 08 '20 at 03:54
  • Why are you setting `funcp` to `nullptr` then reassigning it? A simple `fptr funcp = times;` would suffice in this instance. – 1201ProgramAlarm Jul 08 '20 at 04:05
  • @1201ProgramAlarm I initially tried `fptr funcp = times;`, but then I was wondering what would happen if I had to change the value `funcp` points to. – littlecat Jul 08 '20 at 04:08
  • If you need to change it then the assignment would be within a function body. You can't do assignments at the global level (i.e., outside of a function). – 1201ProgramAlarm Jul 08 '20 at 04:10

1 Answers1

0

The problem is that you are trying to do that outside of any function. Try that:

int main()
{
    funcp = times;
    return 0;
}

Your question has nothing special for C++17. To make it a little more modern and easier to read you may use the using instead of typedef:

using fptr = int (*)(int, int);
Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
  • 1
    Another way, to avoid repetition, is `using fptr = decltype(times) *;` (although personally I would use a non-pointer typedef) – M.M Jul 08 '20 at 04:08