c++syntax-errorfunction-pointersglobal-scope

Assignment to a function pointer in the global scope


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;
}

Solution

  • 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);